2011-11-22 60 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); 

,我認爲這是可行的。沒有測試它,但我認爲這樣做。但是如果我這樣做的話,我可能會設置數據綁定。