0

I try to use combobox in winforms project.

Here is my code:

 private void ShowContoursForm_Load(object sender, EventArgs e) { cbxSelectShape.DisplayMember = dataSetObject.ObjectShapes.ShapeNameColumn.ColumnName; cbxSelectShape.ValueMember = dataSetObject.ObjectShapes.ShapeIDColumn.ColumnName; cbxSelectShape.DataSource = dataSetObject.ObjectShapes; } private void cbxSelectShape_SelectedValueChanged(object sender, EventArgs e) { var id= (int)cbxSelectShape.SelectValue; } 

When I choose item from ComboBox SelectedValueChanged is fired,and id variable gets null.

I need to get value of selected item but I always get null in id variable. Any idea why do I get wrong result and how to fix this code?

4
  • 1
    Try using the SelectedIndexChanged event: msdn.microsoft.com/en-us/library/… Commented Jan 24, 2013 at 13:49
  • While this almost certainly isn't the best way to achieve what you try to achieve, it should work IMO. Commented Jan 24, 2013 at 13:57
  • Rev what is the best way? Commented Jan 24, 2013 at 13:59
  • What's the underlying type of ShapeIDColumn.ColumnName? Is it string? If so, it looks like you're trying to cast each value from string to int. Commented Jan 24, 2013 at 14:04

2 Answers 2

2

You can get the index of ComboBox this way:

private void cbxSelectShape_SelectedValueChanged(object sender, EventArgs e) { var id= ((ComboBox)sender).SelectedIndex; } 
Sign up to request clarification or add additional context in comments.

Comments

1

You should use SelectedValue property of combobox to get value, associated with ValueMember (ShapeID in your case):

var id = ((ComboBox)sender).SelectedValue; 

SelectedIndex returns index of item selected in combobox. Also if this handler used for one combobox, you don't need to cast sender - simply use your combobox variable:

var id = cbxSelectShape.SelectedValue; 

1 Comment

@Michael are you sure you have data in your table? Set a breakpoint and watch for cbxSelectShape.Items[cbxSelectShape.SelectedIndex]. What do you see? BTW your id variable cannot be null if you are casting to int.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.