1

I need to get data from the table item_details and need to bind to a combobox.

There are two columns item_id and item_name. I want to load all the data in item_id column to the combobox and when the selected value of the combobox is changing it should reflect to a textbox showing the corresponding string value of the item_name column.

so far I tried two ways,

http://www.c-sharpcorner.com/uploadfile/syedshakeer/bind-combobox-in-wpf/ http://www.codeproject.com/Articles/20439/WPF-DataBinding

but the problem is nothing is shown in the combobox.

here is my code.

public partial class ComboBoxBinding : Window
{
    private readonly MySqlConnection _connection;
    public ComboBoxBinding()
    {
        InitializeComponent();

        _connection = new MySqlConnection("server=localhost;user  id=*****;password=******;database=onion;persistsecurityinfo=True");
        var dataAdapter = new MySqlDataAdapter("SELECT item_id, item_name FROM item_details", _connection);


        DataSet ds = new DataSet();
        dataAdapter.Fill(ds, "item_details");

        // Method1
        cmbItem1.ItemsSource = ds.Tables[0].Columns["item_id"].ToString();

        cmbItem1.DisplayMemberPath = ds.Tables[0].Columns["item_id"].ToString();
        cmbItem1.SelectedValuePath = ds.Tables[0].Columns["item_name"].ToString();
        // End of the Method1


        // Method2
        cmbItem1.DataContext = ds.Tables["item_details"].DefaultView;
        cmbItem1.DisplayMemberPath = ds.Tables["item_details"].Columns["item_id"].ToString();
        cmbItem1.SelectedValuePath = ds.Tables["item_details"].Columns["item_name"].ToString();
        // End of the Method2
    }


    ~ComboBoxBinding()
    {
        _connection.Close();
    }

    private void cmbItem1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        itemName1.Text = cmbItem1.SelectedValue.ToString();
    }
}

}

Note I tried Method1 and Method2 separately but both are included in here in the same code just for the representation.

Can anyone suggest me what is the mistake?

1 Answer 1

1

Finally got it :) To display the details, code should be as follows(instead of Method1 and Method2)

DataSet ds = new DataSet();
dataAdapter.Fill(ds, "item_details");
DataTable dt = ds.Tables[0];
cmbItem1.ItemsSource = ((IListSource) dt).GetList();
cmbItem1.DisplayMemberPath = "item_id";
cmbItem1.SelectedValuePath = "item_name";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.