2010-09-22 46 views
0

我填充一個DataGridView,像這樣的對象:數據源的DataGridView是空

 foreach (NavField field in this.Fields) 
     { 
      DataGridViewColumn column = new DataGridViewColumn(); 
      column.HeaderText = field.Caption; 
      column.Name = field.FieldNo.ToString(); 
      column.ValueType = field.GetFieldType(); 
      column.CellTemplate = new DataGridViewTextBoxCell(); 

      grid.Columns.Add(column); 
     } 

     int count = 0; 
     foreach (NavRecord record in this.Records) 
     { 
      grid.Rows.Add(); 
      foreach (NavItem item in record.items) 
      { 
       //Adding the rows 
       grid.Rows[count].Cells[item.FieldNo.ToString()].Value = item.RecordValue; 

      } 
      count++; 
     } 

但網格的數據源保持空。是否有其他解決方案來填充網格或更新數據源?

回答

0

創建DataTable並將其綁定到DataGrid。

dataGrid.DataSource = dataTable 
+0

在第二個循環中,爲了添加行(我沒有包含在問題中),還有其他一些條件需要滿足。而且,根據某些條件將行映射到字段上,而不僅僅是列的索引。 對於數據源,我認爲我們可以將datagridview推送到數據源。那可能嗎? 我沒有使用數據表,因爲datatable沒有在datagridview上正確映射,有像headertext這是標題在數據表或隱藏列的做法不同。 – 2010-09-24 07:13:36

1

數據源爲空,因爲您從未設置它。

您可以簡單地設置grid.DataSource = this.Records並完全跳過第二個foreach循環。這將要求您還設置添加到網格中的每列的DataPropertyName

雖然(除非您爲此發佈代碼,否則無法肯定地說,這可能不適用於您的自定義NavRecord類沒有一些修改。

foreach (NavField field in this.Fields) 
{ 
    DataGridViewColumn column = new DataGridViewColumn(); 
    column.HeaderText = field.Caption; 
    column.Name = field.FieldNo.ToString(); 
    column.ValueType = field.GetFieldType(); 
    column.CellTemplate = new DataGridViewTextBoxCell(); 
    // added: 
    column.DataPropertyName = field.FieldNo.ToString(); 

    grid.Columns.Add(column); 
} 

grid.DataSource = this.Records; 

哦,你可能想使用這種方法時設置grid.AutoGenerateColumns = false;否則每列可能會出現兩次。

+0

Grid.Rows和Grid.Columns與DataTable行和列不同。 當您操縱Grid.Rows和Grid.Columns時,您只能操作佈局。 如果將數據綁定到DataGrid,則必須將數據設置爲Bernhof所說的 – 2010-09-22 08:24:38

+0

在第二個循環中,爲了添加行(我沒有將其包含在問題中),我還有其他一些條件需要滿足。而且,根據某些條件將行映射到字段上,而不僅僅是列的索引。 對於數據源,我認爲我們可以將datagridview推送到數據源。那可能嗎? – 2010-09-24 10:01:01

+0

我不確定將datagridview推送到數據源是什麼意思 - 您能否詳細說明一下? – bernhof 2010-09-24 11:02:59