2012-07-05 59 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中。