Get the combobox text in C#


Question

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.

1
6
8/5/2010 11:22:59 AM

Accepted Answer

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
11/24/2008 8:14:43 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon