0

以下代码(完全相同)在另一个项目上运行良好。

 private void AddComboBoxCells()
        {
            DataGridViewComboBoxCell dgvcell;
            _query = "select ProductName from Product";
                com = new SqlCommand(_query, con);
                    for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
                    {
                        dgvcell = new DataGridViewComboBoxCell();
                        dataGridView1[1, i] = dgvcell;
                        myrdr = com.ExecuteReader();
                        while (myrdr.Read())
                        {
                            dgvcell.Items.Add(myrdr.GetValue(0));
                        }
                        myrdr.Close();
                    }

        }

在这个项目上,目前我正在尝试运行相同的代码,但在运行时出现以下错误:

在此处输入图像描述

我正在做的是我正在提取记录,即产品名称并将其填充到 datagridviewcomboboxcell 的第二列中。

编辑

 private void btnAdd_Click(object sender, EventArgs e)
    {
        DataRow dtr = tblOrders.NewRow();
        tblOrders.Rows.Add(dtr);
        DataGridViewComboBoxCell dgvcell;
        _query = "select * from Product";
        com = new SqlCommand(_query, con);
            dgvcell = new DataGridViewComboBoxCell();
            dataGridView1[1, dataGridView1 .Rows.Count -2 ] = dgvcell;
            myrdr = com.ExecuteReader();
            while (myrdr.Read())
            {
                dgvcell.Items.Add(myrdr[0]);
            }
            myrdr.Close();
    }

此添加按钮代码有效,因此传入的数据肯定有效。请协助。

4

2 回答 2

2

首先,您可能希望将处理程序附加到 DataGridView 控件的 DataError 事件,以获取有关您遇到的错误的更多信息。

其次,要检查的明显内容是您在第二个项目中使用的数据上下文。这似乎很可能不一定是编程错误,而更像是与您正在查询和/或进行数据绑定的基础数据相关的问题。

您可能想要调查数据类型和查询返回的值select ProductName from Product

myrdr.getValue(0)- 像这样重写这一行dgvcell.Items.Add(myrdr.GetValue(0));

object val = myrdr.GetValue(0);  
dgvcell.Items.Add(val);         // put a break-point here and check val

编辑

要回答有关如何处理 DataError 事件的问题,您只需将处理程序附加到“dataGridView1”对象的事件成员(如果您不知道什么是事件,或者如何将处理程序附加到事件)在 C# 中,那么我建议你在网上做一些阅读 - 到处都有大量的资源)

// you will want to add this code to attach the handler in your initialization code - maybe in the Load event handler
dataGridView1.DataError += new DataGridViewDataErrorEventHandler(DataGridView1);

// ....

// an then define this function somewhere in your class to handle the event
private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)
{
     // this function will be called when an error occurs.
     //  you can then use the anError paramenter to get insight into the type and cause of the error
}
于 2012-10-31T14:50:56.140 回答
2

您的第二个项目中是否有有效数据?我您的调用myrdr.GetValue(0)在某个时候返回 null (或其他一些虚假值)?

于 2012-10-31T14:55:45.980 回答