C# 根据SelectedIndex设置组合框文本

C# 根据SelectedIndex设置组合框文本,c#,.net,vb.net,winforms,combobox,C#,.net,Vb.net,Winforms,Combobox,我试图根据SelectedIndex设置ComboBox的Text属性,但问题是Text在更改ComboBox的索引后变为字符串。空的 组合框中的每个项目对应于DataTable中的一个字符串,该字符串有两列Name,Description 我需要的是当用户选择某个名称(索引更改)时,我希望在组合框中显示该名称的描述 我所尝试的: private void tbTag_SelectionChangeCommitted(object sender, EventArgs e) { // ge

我试图根据SelectedIndex设置ComboBox的
Text
属性,但问题是
Text
在更改ComboBox的索引后变为
字符串。空的

组合框中的每个项目对应于
DataTable
中的一个字符串,该字符串有两列
Name
Description

我需要的是当用户选择某个名称(索引更改)时,我希望在组合框中显示该名称的描述

我所尝试的:

private void tbTag_SelectionChangeCommitted(object sender, EventArgs e)
{
    // get the data for the selected index
    TagRecord tag = tbTag.SelectedItem as TagRecord;

    // after getting the data reset the index
    tbTag.SelectedIndex = -1;

    // after resetting the index, change the text
    tbTag.Text = tag.TagData;
}
我是如何填充组合框的

//load the tag list
DataTable tags = TagManager.Tags;

foreach (DataRow row in tags.Rows)
{
    TagRecord tag = new TagRecord((string)row["name"], (string)row["tag"]);
    tbTag.Items.Add(tag);
}
使用的助手类:

private class TagRecord
{
    public TagRecord(string tagName, string tagData)
    {
        this.TagName = tagName;
        this.TagData = tagData;
    }

    public string TagName { get; set; }
    public string TagData { get; set; }

    public override string ToString()
    {
        return TagName;
    }
}

我认为这是因为,
ComboBox
中的-1索引意味着没有选择任何项目(),而您正试图更改它的文本。我将再创建一个元素(在索引0处),并使其根据所选内容更改文本:

bool newTagCreated = false;

private void tbTag_SelectionChangeCommitted(object sender, EventArgs e)
{

    TagRecord tag = tbTag.SelectedItem as TagRecord;
    TagRecord newtag = null;

    if (!newTagCreated)
    {
      newtag = new TagRecord(tag.TagData, tag.TagName); //here we change what is going to be displayed

      tbTag.Items.Insert(0, newtag);
      newTagCreated = true;
    }
    else
    {
      newtag = tbTag.Items[0] as TagRecord;
      newtag.TagName = tag.TagData;
    }

    tbTag.SelectedIndex = 0;
}
找到了解决办法

private void tbTag_SelectedIndexChanged(object sender, EventArgs e)
{
    TagRecord tag = tbTag.SelectedItem as TagRecord;
    BeginInvoke(new Action(() => tbTag.Text = tag.TagData));
}

当用户选择任何索引时,每次插入一个新项目时,都会为新标签创建一个反向索引。请检查新标签是否已创建,并相应地进行更新。也可能有一种方法可以使用combobox()的
Text
属性执行此操作,但不确定它是否有帮助。谢谢尝试!但我找到了一个解决办法(贴在下面)。