我有一个Datagridview
DatagridviewComboboxColumn
绑定到datasource
,当我从中选择一个值时我想要的是什么
DatagridviewComboboxColumn
该行的其他单元格将显示DatagridviewComboboxColumn
中与datatable
对应的值。
这是我尝试过的代码:
public Form2()
{
DataGridViewComboBoxColumn cmbcolumn = new DataGridViewComboBoxColumn();
DataGridView2.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(DataGridView2_EditingControlShowing);
}
private void DataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
combo.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
combo.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
}
}
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string item = null;
ComboBox cb = (ComboBox)sender;
if (cb.SelectedValue.ToString() != null)
{
item = cb.SelectedValue.ToString();
fillDGV(item, DataGridView2.CurrentRow);
}
}
private void fillDGV(string code, DataGridViewRow row)
{
SqlConnection con5 = new SqlConnection();
con5.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\database.mdf;Integrated Security=True;User Instance=True";
con5.Open();
SqlCommand cmd = new SqlCommand("SELECT LibArticle, Stock FROM Article WHERE CodeArticle = @CodeArticle", con5);
cmd.Parameters.AddWithValue("@CodeArticle", code);
SqlDataReader read = cmd.ExecuteReader();
if (read.Read())
{
row.Cells[1].Value = read[0].ToString();
row.Cells[2].Value = read[1].ToString();
}
}
此代码仅适用于datagridview
的第一行。在第二行,我收到此错误消息:
对象引用未设置为对象的实例
在这一行:
if(cb.SelectedValue.ToString()!= null)
如何解决?
答案 0 :(得分:0)
if(cb.SelectedValue.ToString()!= null)
将您的if条件更改为
if (cb.SelectedValue != null)