public class ComboboxItem {
public string Text { get; set; }
public string Value { get; set; }
public override string ToString() { return Text; }
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedIndex = comboBox1.SelectedIndex;
int selecteVal = (int)comboBox1.SelectedValue;
ComboboxItem selectedCar = (ComboboxItem)comboBox1.SelectedItem;
MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));
}
I'm adding them like:
ComboboxItem item = new ComboboxItem();
item.Text = cd.Name;
item.Value = cd.ID;
this.comboBox1.Items.Add(item);
I keep getting a NullReferenceExeption and not sure why. the text seems to show up just fine.
Try this:
The problem you have with the
SelectedValue
is not converting into integer. This is the main problem so usinge the following code snippet will help you:You are getting
NullReferenceExeption
because of you are using thecmb.SelectedValue
which is null. thecomboBox
doesn't know what is the value of your custom classComboboxItem
, so either do:Or better of is use data binding like:
Try this:
I had a similar error, My Class is
But what I did, I casted my class to the SelectedItem property of the ComboBox. So, i'll have all of the class properties of the selected item.
I hope this helps someone! Cheers!
Try this: