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?
I suggest the following approach:
First: you create some class for your data items:
Second: you use it in place of your anonymous object:
Third: finally you are now able to cast your selected item to the custom data item and get its properties:
Notice here that I used the
SelecetedItemwhich gives you the whole object unlike theSelectedValuewhere you only get thePartyID.If you later change your mind and want to show other properties they will already be available.