2013-08-21 29 views
0

這裏是方法,複製數據表到未不工作的DataGridView,此方法只可以添加列和中的DataGridView空行。任何人可以建議我解決這個問題,而不使用DataGridView的DataSource屬性?我可以在DataGridView中添加DataTable中不使用DataSource屬性

public void CopyDataTableInDataGridView(DataTable table, DataGridView gdv) 
    { 
     if (gdv.Rows.Count > 0) 
      gdv.Rows.Clear(); 

     if (table != null && table.Rows.Count > 0) 
     { 
      foreach (DataColumn _colm in table.Columns) 
      { 
       DataGridViewColumn _col; 

       if (_colm.GetType() == typeof(bool)) 
        _col = new DataGridViewCheckBoxColumn(); 
       else 
        _col = new DataGridViewTextBoxColumn(); 

       _col.Name = _colm.ColumnName; 
       _col.HeaderText = string.Concat(_colm.ColumnName.Select(x => Char.IsUpper(x) ? " " + x : x.ToString())).TrimStart(' '); 
       gdv.Columns.Add(_col); 
      } 

      foreach (DataRow _row in table.Select()) 
      { 
       //Rows getting added in dgv but not data 
       // By adding following line in Code my problem get solved 
       //object[] _items = _row.ItemArray; 
       gdv.Rows.Add(_row); 
      } 
     } 
    } 
+0

你爲什麼不*想要使用'DataSource'屬性? – gunr2171

+0

@ gunr2171因爲我想在DataGridView上做一些操作,但是DataSource限制我這麼做.. –

+0

不太確定你爲什麼不想使用'DataSource'屬性。目前您正在添加每行的「ToString」實現,而應該爲每行添加一行數據。你可以看到在[這個問題](http://stackoverflow.com/questions/10063770/c-sharp-how-to-add-a-new-row-to-datagridview-programmatically/10063825#10063825)添加行在網格視圖中通過代碼 – Habib

回答

0

通過的DataGridView我的問題得到解決加行之前添加以下行。

object[] _items = _row.ItemArray; 
0

您正在嘗試一個DataRow添加到DataGridView中,而不是添加的DataGridViewRow

看什麼VisualStudio中的intelisence告訴你關於DataGridView.Rows.Add()方法。其中有4個:

  • 添加() - 添加一個空行的DataGridView

  • 添加(的DataGridViewRow) - 添加新行(這是你所需要的)

  • 添加(數) - 以DataGridView的增加[計]空行的

  • 添加(對象[])增加了新的行,其值填充它(你也可以用這個)

您目前正在使用最後一個:添加(object [])。編譯器不會抱怨,因爲它將DataGridViewR作爲一個只含有一個對象的對象數組傳遞給它。顯然不是你想要的。

這裏是相關的問題:https://stackoverflow.com/a/9094325/891715

相關問題