【问题标题】:Select an item in a combobox and set the combobox text to a different one?在组合框中选择一个项目并将组合框文本设置为不同的?
【发布时间】:2012-01-17 10:39:20
【问题描述】:

我想创建一个ComboBox,用户可以在其中输入一个整数值到文本区域,但下拉列表包含几个“默认”值。例如,下拉列表中的项目的格式如下:

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

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

我玩过以下事件:SelectedIndexChangedSelectedValueChangedSelectionChangeCommitted,但我无法更改 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...
     }
 }

【问题讨论】:

    标签: c# .net winforms combobox


    【解决方案1】:

    您可以为您的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 状态之间的框切换时更改显示的文本,请尝试以下操作:(这是一个概念,不确定会如何表现)

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

    【讨论】:

    • 谢谢,与您的概念完美契合! (我已编辑您的代码以添加 selectedIndex 的存储和恢复以保留修改)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多