0

我有一个DatagridviewDatagridviewComboboxColumn它绑定到的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)

怎么解决??

4

1 回答 1

0

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

将您的 if 条件更改为

if (cb.SelectedValue != null)
于 2015-01-21T08:43:21.767 回答