Can't get Value from ComboBox

前端 未结 6 2094
时光取名叫无心
时光取名叫无心 2021-01-15 16:04

I have a simple comboBox with some Value/Text items in it. I have using ComboBox.DisplayMember and ComboBox.ValueMember to correctly set the value/text. When I try to get th

6条回答
  •  孤街浪徒
    2021-01-15 16:54

    Not sure what ComboBox.SelectedValue means, it has a SelectedItem property. That would not be set when you add an item, only when the user makes a selection.

    The Items property is a collection of System.Object. That allows a combo box to store and display any kind of class object. But you'll have to cast it from object to your class type to use the selected object in your code. That can't work in your case, you added an object of an anonymous type. You'll need to declare a small helper class to store the Value and Text properties. Some sample code:

      public partial class Form1 : Form {
        public Form1() {
          InitializeComponent();
          comboBox1.Items.Add(new Item(1, "one"));
          comboBox1.Items.Add(new Item(2, "two"));
          comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged);
        }
        void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
          Item item = comboBox1.Items[comboBox1.SelectedIndex] as Item;
          MessageBox.Show(item.Value.ToString());
        }
        private class Item {
          public Item(int value, string text) { Value = value; Text = text; }
          public int Value { get; set; }
          public string Text { get; set; }
          public override string ToString() { return Text; }
        }
      }
    

提交回复
热议问题