2009-01-01 35 views
3

如何以編程方式向C#中的DataGridTable添加行?當用戶選擇一個選項,我想重新填充DataGridTable新鮮的數據,這我獲得如下圖所示:以編程方式將行添加到DataGridTable

 connect.Open(); 
     MySqlCommand comm = connect.CreateCommand(); 
     comm.CommandText = getCustomerInvoices + customerID + "\'"; 
     MySqlDataReader r = comm.ExecuteReader(); 
     while (r.Read()) 
     { 
      DataGridViewRow d = new DataGridViewRow(); 
      String[] parameters = new String[5]; 
      parameters[0] = r.GetValue(0).ToString(); 
      parameters[1] = r.GetValue(1).ToString(); 
      parameters[2] = r.GetValue(2).ToString(); 
      parameters[3] = r.GetValue(3).ToString(); 
      parameters[4] = r.GetValue(4).ToString(); 
      d.SetValues(parameters); 
      invoiceTable.Rows.Add(d); 
     } 
     connect.Close(); 

有什麼事發生的是,我得到添加到表新行,但舊行仍然存在,新行看起來沒有任何值(一堆空白文本框,我知道這個查詢在我的測試用例中返回了一個結果)。

有人可以向我解釋我必須做什麼嗎?

回答

3

我相信Rows.Add()對字符串數組有一個重載。如果你正在創建一個字符串數組,爲什麼不嘗試使用它呢?的 即代替:

d.SetValues(parameters); 
invoiceTable.Rows.Add(d); 

你會JUSE使用:

invoiceTable.Rows.Add(parameters); 

或者,如果你仍然想創建一個的DataGridViewRow對象,並呼籲它setValues方法,我認爲你需要或者投數組到一個Object類型的數組,或者傳遞每個值作爲它自己的參數而不是傳遞數組。

+0

感謝之前,我不知道重載版本。它現在有效。 – Elie 2009-01-01 04:14:46

3

我相信你需要調用.CreateCells(GridName)調用的setValue

相關問題