naf-naf
naf-naf

Reputation: 103

ComboBox selected text or item

I'm working in winform I try a lot of times to catch the text of the comboBox selected item, and I can not, it's always empty, this is code

List<person>op = new List<person>(); op=DAL_O.per();
        foreach(person rt in op )
        {
            comboBox1.DataSource = op;
            comboBox1.DisplayMember = "Name_person";
            comboBox1.ValueMember = "id_person";
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {

      Lbl_full_list.Text+=comboBox1.Items[comboBox1.SelectedIndex].ToString();
//or
      Lbl_full_list.Text+= comboBox1.Text;


    }

Maybe someone has an idea? I searched a lot on Google and the results did not work

Upvotes: 3

Views: 23135

Answers (3)

Waqas
Waqas

Reputation: 6802

First of all why are you using foreach loop? You can bind it simple like this:

List<person>op = new List<person>(); 
op=DAL_O.per();
comboBox1.DataSource = op;
comboBox1.DisplayMember = "Name_person";
comboBox1.ValueMember = "id_person";

And regarding your original question, try:

Lbl_full_list.Text += comboBox1.Text

Upvotes: 0

Iain Ward
Iain Ward

Reputation: 9936

For a start, you don't want to bind each person in the list to the combo box otherwise you'' only have a maximum of one item in the list, you just want to bind the whole list so remove the loop. And also you can combine the list declaration and setting into one line to get this (you could even skip using List, but I've left it in for readablity:

List<person>op = DAL_O.per();

comboBox1.DataSource = op;
comboBox1.DisplayMember = "Name_person";
comboBox1.ValueMember = "id_person";

And as for getting the selected text value, I'd use either

comboBox1.Text

or (as per MSDN example)

comboBox1.SelectedItem.ToString()

Upvotes: 0

leppie
leppie

Reputation: 117220

Your binding code is incorrect.

Removing the foreach around it, should fix the issue.

Upvotes: 2

Related Questions