user1372430
user1372430

Reputation:

How do i get selected item from combobox which was created with datatable

In my project, combobox values are coming in a method named "getArticles". Here is the method:

public void getArticles(ComboBox cb)
{
    var getAll = getAllFromDB("articles", "", "articleName ASC");
    DataTable dt = getAll.Tables["articles"];
    cb.DataSource = dt;
    cb.DisplayMember = "articleName";
    cb.ValueMember = "id";
}

"getAllFromDB" method is doing selection from articles table and returns DataSet. Now my problem is here. When i use cb.SelectedValue i can get id value of article name. This is Ok and good. But when i use cb.SelectedItem it is showing "System.Data.DataRowView".
Please could you help me, how can i get article name like using cb.selectedItem?
Kind regards.

Upvotes: 5

Views: 6295

Answers (1)

Try the following codes of lines, may be it will help to get the selected item.

        ComboBoxItem requiredItem = (ComboBoxItem)cboType.SelectedItem;
        string value = requiredItem.Content.ToString();

EDIT:

Sorry, the above ComboBoxItem will only works in the case of .Net Framework 4.5, it is in System.Windows.Controls namespace. Refer to following code parts for your answer and check

        DataTable dtable = (DataTable)comboBox1.DataSource;
        label1.Text = dtable.Rows[comboBox1.SelectedIndex][0].ToString();//gives you article id
        label2.Text = dtable.Rows[comboBox1.SelectedIndex][1].ToString();//gives you article name

Upvotes: 7

Related Questions