【问题标题】:How do I change the text of a ComboBox item?如何更改 ComboBox 项的文本?
【发布时间】:2011-08-11 17:52:01
【问题描述】:

我有一个名为 dataGridView 列的组合框,我可以将组合框中显示的项目的文本更改为我想要的任何文本吗?

for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    if (dataGridView1.Columns[i].ValueType == typeof(string) && 
        i != 6 && 
        i != 7 && 
        i != 8 && 
        i != 9)
            comboBox1.Items.Add(dataGridView1.Columns[i].Name);
}
comboBox1.SelectedIndex = 0;

【问题讨论】:

  • 当然可以,但是请您发布一些代码吗?
  • 是的,您可以这样做。
  • 我编辑了帖子并添加了代码
  • 这是 WPF 还是表单?你也可以标记你的问题吗?谢谢!

标签: c# combobox


【解决方案1】:

如果您要使用的值不适合作为组合框中的文本,我通常会这样做:

public class ComboBoxItem<T> {
    public string FriendlyName { get; set; }
    public T Value { get; set; }

    public ComboBoxItem(string friendlyName, T value) {
        FriendlyName = friendlyName;
        Value = value;
    }

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

// ...
List<ComboBoxItem<int>> comboBoxItems = new List<ComboBoxItem<int>>();                      
for (int i = 0; i < 10; i++) {
    comboBoxItems.Add(new ComboBoxItem<int>("Item " + i.ToString(), i));
}

_comboBox.DisplayMember = "FriendlyName";
_comboBox.ValueMember = "Value";
_comboBox.DataSource = comboBoxItems;


_comboBox.SelectionChangeCommitted += (object sender, EventArgs e) => {
    Console.WriteLine("Selected Text:" + _comboBox.SelectedText);
    Console.WriteLine("Selected Value:" + _comboBox.SelectedValue.ToString());
};

【讨论】:

    【解决方案2】:

    希望对你有帮助:

    combobox.Items[combobox.FindStringExact("string value")] = "new string value";
    

    FindStringExact 方法返回特定项目文本的索引,因此这是更改 Combobox 项目文本的更好方法。

    注意:这在 C# 上运行良好。

    【讨论】:

    • 从来不知道我可以像这样编辑项目的文本。 combobox.Items[int index]= "new text";
    【解决方案3】:

    试试这个:

    ListItem item = comboBox1.Items.FindByText("<Text>");
    if (item != null)
    {
       item.Text = "<New Text>";
    }
    

    【讨论】:

    • 我认为他想保留列名的值,但显示一些更直观的东西或者只是格式更好。
    • 如果是这样的话,他不能将item值设置为实际的列名,并将文本更改为更易读/直观的东西吗?
    • 我假设他正在使用 Winforms;除非他设置 DataSource 并填充 DisplayMember 和 ValueMember 或使用分隔文本和值的自定义类,否则不要认为您可以这样做。
    【解决方案4】:

    可能不是更改文本,而是从特定索引中删除项目并在具有新文本的相同索引处插入新项目会很简单

    【讨论】:

      【解决方案5】:

      您可以通过以下方式简单地更改组合框项目文本:

      my_combo.Items [i_index] = "some string"; 
      

      【讨论】:

        【解决方案6】:

        最好的方法是这样:

        ui->myComboBox->setItemText(index,"your text");
        

        【讨论】:

        猜你喜欢
        • 2018-07-30
        • 2014-03-03
        • 2019-11-07
        • 2012-06-18
        • 1970-01-01
        • 2019-03-24
        • 2011-02-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多