amer
amer

Reputation: 623

How do I change the text of a ComboBox item?

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;

Upvotes: 9

Views: 27149

Answers (6)

Omar Chavez
Omar Chavez

Reputation: 111

I hope this helps you:

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

The FindStringExact method returns the index of an specific item text, so this can be a better way to change the text of a Combobox item.

Note: This works fine on C#.

Upvotes: 7

Angie Quijano
Angie Quijano

Reputation: 4453

The best way you can do that is in this way:

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

Upvotes: 0

user2244507
user2244507

Reputation: 27

You can simply change combo box items text by :

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

Upvotes: 0

gangelo
gangelo

Reputation: 3172

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

Upvotes: 5

Haris Hasan
Haris Hasan

Reputation: 30097

May be instead of changing the text it would be simple to remove the item from a particular index and insert new item at same index with new text

Upvotes: 0

James Johnson
James Johnson

Reputation: 46047

Try this:

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

Upvotes: 1

Related Questions