2011-11-22 62 views
0

我想使用datatable插入数据网格并在程序中定义网格列。请帮助我这个代码有什么错? 以下错误出现“无法转换类型System.String对象System.String类型[]”行不插入窗体datagrid

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(); 
     } 

    } 
+1

如果有任何给定的答案,请接受一些现有的答案,回答了问题! – Coops

+0

哪条线路出现故障? – sq33G

回答

0

我要说的是,rowArray是一个字符串不是字符串[]。

0

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

认为根据你写的内容,你打算做的是在DataGridView中插入一行,因为这是所有的dRows持有是一个表行。你的代码部分来自MSDN example 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); 

,我认为这是可行的。没有测试它,但我认为这样做。但是如果我这样做的话,我可能会设置数据绑定。