I’ve comboBox in windows forms which I’ve bound to datasource, which is correctly returning Id associated with particular name in combobox whenever form loads.
private void PurchaseMaster_Load(object sender, EventArgs e)
{
DataTable dt = productMasterBAL.GetTable("Select * from productMaster");
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "ProductName";
combBox1.ValueMember = "ProductId";
}
But whenever I select any value in Combobox I get:
NullReferenceException was unhandled. Object reference not set to an
instance of an object
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView row = comboBox1.SelectedValue as DataRowView;
MessageBox.Show(String.Format("{0}", row["ProductId"])); //This line is causing exception
}
Could anyone please tell how can I solve this problem?
You should be checking for the values like this
This should give you the selected Product Id in the combobox
The items in Combobox are stored as
ObjectCollectionand not exactly a DataRow or DataRowView as you seem to be expecting.