Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the text of a ComboBox item?

Tags:

c#

combobox

I have a combobox filed with the name of dataGridView columns, can I change the text of 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;
like image 500
amer Avatar asked Aug 11 '11 17:08

amer


People also ask

How do I edit items in ComboBox?

Double-click an item to edit the name of the item.

How do I make my combo box not editable?

To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this: stateComboBox.


1 Answers

If the value you want to use is not suitable as the text in a 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());
};
like image 126
gangelo Avatar answered Sep 18 '22 14:09

gangelo