在SelectedIndex的基础上设置ComboBox文本

时间:2013-05-21 05:53:25

标签: c# .net vb.net winforms combobox

我试图在SelectedIndex的基础上设置ComboBox的Text属性,但更改了Combobox的索引后问题Text变为String.Empty

ComboBox中的每个项目对应DataTable中包含2列NameDescription

的字符串

当我想在ComboBox

中显示其描述时,我需要的是当用户选择名称(索引更改)时

我尝试了什么:

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;
}

我如何填充Combobox

//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;
    }
}

2 个答案:

答案 0 :(得分:0)

我认为这是因为ComboBox中的-1索引意味着没有选择任何项目(msdn)并且您正在尝试更改它的文本。我将创建一个元素(在索引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;
}

答案 1 :(得分:0)

找到解决方案。

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