2012-01-17 74 views
2

我想创建一个ComboBox用户可以在文本区域中输入一个整数值,但下拉列表包含几个“默认值”值。例如,在下拉列表中的项目会采用以下格式:选择组合框中的项目并将组合框文本设置为不同的项目?

  • 默认 - 0
  • 值1 - 1
  • 值2 - 2

我要的是当用户选择一个项目时(例如“默认 - 0”),ComboBox文本将只显示数字“0”而不是“默认 - 0”。单词“默认”只是信息文本。

我玩过以下活动:SelectedIndexChanged,SelectedValueChangedSelectionChangeCommitted,但我无法更改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... 
    } 
} 

回答

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

[编辑] 如果你想改变显示文本时,下拉状态之间盒toogles试试这个:(这是一个概念,不知道如何表现)

private void comboBox1_DropDown(object sender, EventArgs e) 
    { 
     comboBox1.DisplayMember = "Description"; 
    } 

    private void comboBox1_DropDownClosed(object sender, EventArgs e) 
    { 
     comboBox1.DisplayMember = "Value"; 
    } 
+0

谢谢,与您的理念完美合作! (我编辑了你的代码来添加selectedIndex的存储和恢复以保持修改) – 2012-01-17 13:10:17