Search code examples
c#winformscomboboxvaluemember

Can't read the value member setting from the data reader to combobox


I'm setting the value member and display member from a datareader to combobox like this.

public void getPartyNamesCombo()
{
    SqlDataReader reader = new VotingOP().getPartyNamesToCombo();
    while (reader.Read())
    {
        cmbPartyName.Items.Add(new { PartyID = reader["partyID"].ToString(), PartyName = reader["partyName"].ToString() });
    }
    cmbPartyName.ValueMember = "PartyID";
    cmbPartyName.DisplayMember = "PartyName";
}

I'm trying to access the id like this

int selectedValue = (int)cmbPartyName.SelectedValue;
MessageBox.Show("Selected value is"+selectedValue);

but it gives me "An unhandled exception of type 'System.NullReferenceException'" Exception. What's wrong I'm doing here?


Solution

  • I suggest the following approach:

    First: you create some class for your data items:

    class MyDataItem 
    {
        public string PartyID { get;set; }
        public string PartyName { get;set; }
    }
    

    Second: you use it in place of your anonymous object:

    public void getPartyNamesCombo()
    {
        SqlDataReader reader = new VotingOP().getPartyNamesToCombo();
        while (reader.Read())
        {
            cmbPartyName.Items.Add(new MyDataItem() { 
                PartyID = reader["partyID"].ToString(), 
                PartyName = reader["partyName"].ToString() 
            });
        }
        cmbPartyName.ValueMember = "PartyID";
        cmbPartyName.DisplayMember = "PartyName";
    }
    

    Third: finally you are now able to cast your selected item to the custom data item and get its properties:

    MyDataItem selectedItem = cmbPartyName.SelectedItem as MyDataItem;
    if (selectedItem != null) 
    {
        MessageBox.Show(String.Format("You've just selected the '{0}' party with the ID {1}",  selectedItem.PartyName, selectedItem.PartyID));
    }
    

    Notice here that I used the SelecetedItem which gives you the whole object unlike the SelectedValue where you only get the PartyID.

    If you later change your mind and want to show other properties they will already be available.