【问题标题】:Rows are not insert in windows form datagrid行未插入到 Windows 表单数据网格中
【发布时间】:2012-01-04 04:05:39
【问题描述】:

我想使用数据表插入数据网格并在程序中定义网格列。请帮我看看这段代码有什么问题??? 出现以下错误“无法将 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();
        }

    }

【问题讨论】:

  • 如果任何给出的答案回答了问题,请接受您现有的一些已回答问题!

标签: c# winforms datagrid datatable


【解决方案1】:

您正在遍历 object[] 并将该数组中的元素视为 string[] 并且该数组的元素 0 肯定是 string 而不是 string[]

认为根据您所写的内容,您打算做的是将单行插入 DataGridView,因为 dRows 只保留一个表格行。您的代码部分来自 MSDN 示例 here,如果您查看该示例的工作原理,您会发现它们构建了一堆 string[] 以将 unbound 行添加到数据网格视图。

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

你可以这样做:

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

我认为这会奏效。没有测试它,但我认为它会做到这一点。但如果我这样做的话,我可能会设置数据绑定。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 2013-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-16
      相关资源
      最近更新 更多