2012-07-05 61 views
0

我正在嘗試將新行添加到公共函數中的現有datagridview。每當我嘗試訪問datagridview的任何數據屬性時,我都會得到空值。 datasource屬性爲null,因此我無法向其添加新元素。我創建了一個新的datagridviewrow,但CreateCells方法不會複製列並引發超出邊界錯誤的索引。有人知道我在這裏試圖做什麼可能是錯的嗎?無法將行添加到委託函數中的datagridview中

這裏是整個函數的代碼:

public void AddToGrid(Attendance newRecord) 
    { 
     try 
     { 
      DataGridViewRow newRow = new DataGridViewRow(); 
      newRow.CreateCells(AttendanceGrid); 
      newRow.Cells[1].Value = newRecord.EmployeeNumber; 
      newRow.Cells[2].Value = newRecord.ScheduledDate; 
      newRow.Cells[3].Value = newRecord.SIn; 
      newRow.Cells[4].Value = newRecord.SOut; 
      newRow.Cells[5].Value = newRecord.AIn; 
      newRow.Cells[6].Value = newRecord.AOut; 
      newRow.Cells[7].Value = newRecord.RecordCode; 
      newRow.Cells[8].Value = newRecord.ReasonCode; 
      newRow.Cells[9].Value = newRecord.Comments; 

      AttendanceGrid.Rows.Add(newRow); 
      AttendanceGrid.Refresh(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message + ": " + ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
     } 
    } 

任何人都可以看到我在做什麼的問題?

+0

您是否正在使用DatagridView的Datatable等數據源? – Derek 2012-07-09 08:41:21

回答

1

您應該有DatagridView的數據源,如DataTable。

然後,您通過綁定源將該DataTable綁定到Datagridview。

您可以向DataTable添加新行,然後DataTable會自動反映到Datagrid中。