How to change the text of a ComboBox element?

I have a combo box with the column name dataGridView, can I change the text of the displayed items in the comboBox to any text I want?

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;
+5
source share
6 answers

If the value you want to use is not suitable as text in combobox, I usually do something like this:

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());
};
+4
source

Hope this helps you:

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

The method FindStringExactreturns the index of the specific text of the element, so this may be the best way to change the text of the element Combobox.

Note. This works fine in C #.

+2
source

:

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

Maybe instead of changing the text, it would be simple to remove an element from a specific index and insert a new element into the same index with new text

0
source

You can simply change the text of the list items:

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

The best way to do this is as follows:

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

All Articles