user367509
user367509

Reputation: 59

Get the select value from a combobox that is bound to a dataset

I want to get the select value from a combobox that is bound to a dataset.

For binding the combobox I use:

cboEmployees.DataSource = ds.Tables["employees"];
cboEmployees.ValueMember = "employee_number";
cboEmployees.DisplayMember = "employee_name";

To get selected value:

string SelectedValue = cboEmployees.SelectedValue.ToString();

I got this error message: Object reference not set to an instance of an object.

Could anyone help me with this?

Thanks in advance!

Upvotes: 1

Views: 1822

Answers (1)

VoodooChild
VoodooChild

Reputation: 9784

you should be setting the cboEmployees.ItemsSource. The reason for the error is because your:

cboEmployees.SelectedValue is null and ToString() method can not be called on it.

EDIT: just thinking about this more and I think should be used like so:

cboEmployees.DataSource = ds.Tables("Employee");
cboEmployees.ValueMember = ds.Tables[0].Columns[0].ToString();
cboEmployees.DisplayMember = ds.Tables[0].Columns[1].ToString();

col[0] is employee number and col[1] would be employee_name

Hope this helps!!!

Upvotes: 2

Related Questions