行不是在窗体中插入数据网格

时间:2011-11-22 19:15:49

标签: c# winforms datagrid datatable

我想使用datatable插入数据网格,并在程序中定义网格列。请帮我这个代码有什么问题??? 发生以下错误“无法将System.String类型的对象强制转换为类型System.String []”

 enter code here 
SqlConnection connection;
    string query;
    SqlCommand cmd;
    SqlDataAdapter da;
    DataSet ds;
    DataRow dRows;
    public void ViewGrid()
    {
    connection = new SqlConnection(ConnString);
        try
        {
            connection.Open();
            query = @"SELECT * FROM TBLWorkers";
            //cmd = new SqlCommand(query, connection);
            da = new SqlDataAdapter(query, connection);
            ds = new DataSet();
            da.Fill(ds, "Workers");

            int MaxRows = ds.Tables["Workers"].Rows.Count;

            label1.Text = MaxRows.ToString();

            dRows = ds.Tables["Workers"].Rows[0];


            // Create an unbound DataGridView by declaring a column count.
            dataGridView1.ColumnCount = 4;
            dataGridView1.ColumnHeadersVisible = true;

            // Set the column header names.
            dataGridView1.Columns[0].Name = "Recipe";
            dataGridView1.Columns[1].Name = "Category";
            dataGridView1.Columns[2].Name = "Main Ingredients";
            dataGridView1.Columns[3].Name = "Rating";

            object[] rows1 = new object[] { dRows[0].ToString(), dRows[1], dRows[2], dRows[3] };
            foreach (string[] rowArray in rows1)
            {
                dataGridView1.Rows.Add(rowArray);
            }

        }
        catch (Exception x)
        {
            MessageBox.Show(x.Message);
            connection.Close();
        }

    }

2 个答案:

答案 0 :(得分:0)

我会说rowArray是一个字符串而不是字符串[]。

答案 1 :(得分:0)

您正在迭代object[]并将该数组中的元素视为string[],该数组的元素0绝对是string而不是string[]

认为你打算做什么,基于你所写的,是在DataGridView中插入一行,因为所有dRows保持的是一个表行。您的代码部分来自MSDN示例here,如果您查看该示例的工作原理,您会看到它们构建了一堆string[]来添加未绑定的到DataGridView的行。

这就是你想要做的吗?添加未绑定的行?你已经有了DataTable。您可以使用数据绑定来解决此问题,而不是从数据库中检索数据,然后将其复制到object[]中,只需转向并将其放入未绑定的DataGridView中。

你可以这样做:

string[] myRow = new string[] { dRows[0].ToString(), dRows[1].ToString(), dRows[2].ToString(), dRows[3].ToString() };
dataGridView1.Rows.Add(myRow);

我觉得那会有用。没有测试它,但我认为那样做。但是如果我这样做,我可能会设置数据绑定。