Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the combobox text in C#

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.

Here's the code:

public BookType type
{
    get
    {
        return (BookType)Enum.Parse(typeof(BookType), this.typeComboBox.Text);
    }
    set
    {
        this.typeComboBox.Text = value.ToString();
    }
}

For some reason, this.typeComboBox.Text always returns an empty string when I select an item on the combobox.

Does someone see what I'm doing wrong?

EDIT: I have come to the conclusion that the problem lies in timing. The point in time at which I summon the text is indeed after I changed the combobox, but still before that value is parsed as a value. Problem fixed in a different way now, thanks for all the ideas.

like image 998
Vordreller Avatar asked Nov 24 '08 19:11

Vordreller


4 Answers

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

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

like image 72
Muhammedh Avatar answered Nov 13 '22 15:11

Muhammedh


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

like image 28
Rune Grimstad Avatar answered Nov 13 '22 14:11

Rune Grimstad


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...

like image 1
Vordreller Avatar answered Nov 13 '22 14:11

Vordreller


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

like image 1
Dylan Beattie Avatar answered Nov 13 '22 14:11

Dylan Beattie