Get the combobox text in C#

后端 未结 6 1575
甜味超标
甜味超标 2020-12-18 04:08

I filled up a combobox with the values from an Enum.

Now a combobox is text right? So I\'m using a getter and a setter. I\'m having problems reading the text.

相关标签:
6条回答
  • 2020-12-18 04:21

    Try this. this worked for me.

    string selectedText = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
    

    The GetItemText method analyzes the item and returns the text of the bound to that item.

    0 讨论(0)
  • 2020-12-18 04:21

    You should try this.typeComboBox.SelectedItem.ToString()

    0 讨论(0)
  • 2020-12-18 04:24

    Set the DropDownStyle of the ComboBox to DropDownList. This will ensure that only the elements already in the list can be selected (no need to check that the text actually is a valid value). Then if you use Enum.GetValues(typeof(BookType)) to fill the combobox then typeComboBox.SelectedItem property will be a value of BookType. So you can use this in the property getter and setter.

    So to summarize. You don't have to bind the combobox to a list of text values as long as you use the DropDownList style. Use the SelectedItem property to get an item of the wanted type instead of checking the Text property.

    Edit: You may have to check the SelectedItem property for null

    0 讨论(0)
  • 2020-12-18 04:29

    Have you tried using this.typeComboBox.SelectedText instead of typeComboBox.Text ?

    0 讨论(0)
  • 2020-12-18 04:32

    I just created a simple windows form, and everything worked okay for me. Here is the code.

    public enum Test
    {
        One, Two, Three
    }
    
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
    
            this.comboBox1.DataSource = Enum.GetNames(typeof(Test));
        }
    
        public Test Test
        {
            get 
            {
                return (Test)Enum.Parse(typeof(Test), this.comboBox1.Text);
            }
            set
            {
                this.comboBox1.Text = value.ToString();
            }
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(this.Test.ToString());
    
            this.Test = Test.Two;
    
            MessageBox.Show(this.Test.ToString());
        }
    }
    
    0 讨论(0)
  • 2020-12-18 04:39

    The combobox starts at index -1, which has no text, thus an empty string: ""

    I then change the index to a BookType that I need and then I get the wrong output...

    0 讨论(0)
提交回复
热议问题