1

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

ComboBox 中的每个 Item 对应于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;
}

我如何填充组合框

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

2 回答 2

0

找到了解决方案。

private void tbTag_SelectedIndexChanged(object sender, EventArgs e)
{
    TagRecord tag = tbTag.SelectedItem as TagRecord;
    BeginInvoke(new Action(() => tbTag.Text = tag.TagData));
}
于 2013-05-21T06:15:53.890 回答
0

我认为发生这种情况是因为 -1 index inComboBox意味着没有选择任何项目(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;
}
于 2013-05-21T06:07:08.140 回答