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 < dataGridVi开发者_JS百科ew1.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;
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#.
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());
};
Try this:
ListItem item = comboBox1.Items.FindByText("<Text>");
if (item != null)
{
item.Text = "<New Text>";
}
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
You can simply change combo box items text by :
my_combo.Items [i_index] = "some string";
The best way you can do that is in this way:
ui->myComboBox->setItemText(index,"your text");
精彩评论