Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting selected value of a combobox

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.

like image 360
maxy Avatar asked Aug 01 '11 15:08

maxy


People also ask

Which method is used to get the selected item in ComboBox control?

The ComboBox class searches for the specified object by using the IndexOf method.

What happens when we select a value from a ComboBox in WPF?

A ComboBox control is an items control that works as a ListBox control but only one item from the collection is visible at a time and clicking on the ComboBox makes the collection visible and allows users to pick an item from the collection. Unlike a ListBox control, a ComboBox does not have multiple item selection.


2 Answers

Try this:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {     ComboBox cmb = (ComboBox)sender;     int selectedIndex = cmb.SelectedIndex;     int selectedValue = (int)cmb.SelectedValue;      ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;     MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));         } 
like image 88
James Hill Avatar answered Sep 25 '22 11:09

James Hill


You are getting NullReferenceExeption because of you are using the cmb.SelectedValue which is null. the comboBox doesn't know what is the value of your custom class ComboboxItem, so either do:

ComboboxItem selectedCar = (ComboboxItem)comboBox2.SelectedItem; int selecteVal = Convert.ToInt32(selectedCar.Value); 

Or better of is use data binding like:

ComboboxItem item1 = new ComboboxItem(); item1.Text = "test"; item1.Value = "123";  ComboboxItem item2 = new ComboboxItem(); item2.Text = "test2"; item2.Value = "456";  List<ComboboxItem> items = new List<ComboboxItem> { item1, item2 };  this.comboBox1.DisplayMember = "Text"; this.comboBox1.ValueMember = "Value"; this.comboBox1.DataSource = items; 
like image 22
Jalal Said Avatar answered Sep 26 '22 11:09

Jalal Said