Search code examples
c#drop-down-menudatasetvaluemember

Add 2 or more field to value member of C# coding


I have table with 4 primary key fields. I load that in to drop down list in my WinForm application created by using C#.

On the TextChanged event of drop down list I have certain TextBox and I want to fill the information recived by the table for the certain field I selected by the drop down list.

So as I say the table having 4 fields. Can I get those all 4 fields into value member from the data set, or could you please tell me whether is that not possible?

Thank you.

Datatable dt=dba.getName(); cmb_name.ValueMember="id"; cmb_name.DisplayMember="name"; cmb_name.DataSource=dt;

this is normal format.. but i have more key fields.. so i need to add more key fields..


Solution

  • You can use DataSource property to bind your source data to the ComboBox (e.g. a List of Entities, or a DataTable, etc), and then set the DisplayMember property of the ComboBox to the (string) name of the field you want to display.

    After the user has selected an Item, you can then cast the SelectedItem back to the original row data type (Entity, DataRow, etc - it will still be the same type as you put in), and then you can retrieve your 4 composite keys to the original item.

    This way you avoid the SelectedValue problem entirely.

    Edit:

    Populate as follows:

    cmb_name.DisplayMember = "name";
    cmb_name.DataSource = dt;
    
    // Ignore ValueMember and Selected Value entirely
    

    When you want to retrieve the selected item

    var selectedRow = (cmb_name.SelectedItem as DataRowView );
    

    Now you can retrieve the 4 values of your PK, e.g. selectedRow["field1"], selectedRow["field2"], selectedRow["field3"] etc

    If however you mean that you want to DISPLAY 4 columns to the user (i.e. nothing to do with your Table Key), then see here How do I bind a ComboBox so the displaymember is concat of 2 fields of source datatable?