【问题标题】:Set ComboBox Text on Basis of SelectedIndex根据 SelectedIndex 设置 ComboBox 文本
【发布时间】:2013-05-21 05:53:24
【问题描述】:

我正在尝试在 SelectedIndex 的基础上设置 ComboBox 的 Text 属性,但问题是 Text 在更改 Combobox 的索引后变为 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;
    }
}

【问题讨论】:

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


    【解决方案1】:

    我认为这是因为 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;
    }
    

    【讨论】:

    • 每次当用户选择任何索引时插入一个新项目并且为 newTag 创建一个反向索引
    • 是的,添加了检查新标签是否已创建并相应更新。
    • 也可能有一种方法可以使用组合框的Text 属性(msdn),但不确定它是否会有所帮助。
    • 感谢您的尝试!但我找到了解决方案(发布在下面)。
    【解决方案2】:

    找到了解决办法。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 2019-05-24
      • 1970-01-01
      • 2017-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多