根据 DatagridviewComboboxCell 值填充 Datatable 中的 Datagridview 行

Fill Datagridview rows from Datatable according to a DatagridviewComboboxCell value

我有一个 DatagridviewDatagridviewComboboxColumn 绑定到一个 datasource,我想要的是当我从中选择一个值时 DatagridviewComboboxColumn 该行的其他单元格将显示对应于 datatable 中的 DatagridviewComboboxColumn 的值。

这是我试过的代码:

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 的第一行。在第二行我收到了这个错误信息:

Object reference not set to an instance of an object

这一行:

if (cb.SelectedValue.ToString() != null)

如何解决?

if (cb.SelectedValue.ToString() != null)

将您的 if 条件更改为

if (cb.SelectedValue != null)