我想创建一个ComboBox
,其中用户可以在文本区域中键入整数值,但下拉列表包含多个“默认值”值。例如,下拉列表中的项目格式如下:
我想要的是当用户选择项目时(例如“默认 - 0”),ComboBox
文本将仅显示数字“0”而不是“默认 - 0”。 “默认”一词只是信息性文字。
我玩过以下活动:SelectedIndexChanged
,SelectedValueChanged
和SelectionChangeCommitted
,但我无法更改ComboBox
的文字。
private void ModificationCombobox_SelectionChangeCommitted(object sender, EventArgs e)
{
ComboBox comboBox = (ComboBox)sender; // That cast must not fail.
if (comboBox.SelectedIndex != -1)
{
comboBox.Text = this.values[comboBox.SelectedItem.ToString()].ToString(); // Text is not updated after...
}
}
答案 0 :(得分:2)
您可以为ComboBox
项定义一个类,然后创建一个List<ComboBoxItem>
并将其用作Combobox.DataSource
。有了这个,您可以将ComboBox.DisplayMember
设置为您想要显示的属性,并且仍然可以从ComboBox_SelectedIndexChanged()
引用您的对象:
class ComboboxItem
{
public int Value { get; set; }
public string Description { get; set; }
}
public partial class Form1 : Form
{
List<ComboboxItem> ComboBoxItems = new List<ComboboxItem>();
public Form1()
{
InitializeComponent();
ComboBoxItems.Add(new ComboboxItem() { Description = "Default = 0", Value = 0 });
ComboBoxItems.Add(new ComboboxItem() { Description = "Value 1 = 1", Value = 1 });
ComboBoxItems.Add(new ComboboxItem() { Description = "Value 2 = 2", Value = 2 });
comboBox1.DataSource = ComboBoxItems;
comboBox1.DisplayMember = "Value";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var item = (ComboboxItem)((ComboBox)sender).SelectedItem;
var test = string.Format("Description is \'{0}\', Value is \'{1}\'", item.Description, item.Value.ToString());
MessageBox.Show(test);
}
}
[编辑] 如果你想在DropDown状态之间的box toogles中更改显示的文本,请尝试:(这是一个概念,不确定它会如何表现)
private void comboBox1_DropDown(object sender, EventArgs e)
{
comboBox1.DisplayMember = "Description";
}
private void comboBox1_DropDownClosed(object sender, EventArgs e)
{
comboBox1.DisplayMember = "Value";
}