I am trying to add a new row to an existing datagridview in a public function. Whenever I try to access any data properties of the datagridview I get null values. The datasource property is null so I cannot add a new element to it. I have created a new datagridviewrow, but the CreateCells method does not copy columns and throws an index out of bounds error. Does anyone know what might be wrong with what I am trying to do here?
Here is the code for the entire function:
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);
}
}
Can anyone see a problem with what I am doing?
You should have a datasource for the DatagridView such as a DataTable.
You then bind that DataTable to the Datagridview via a Binding Source.
You can the add new rows to the DataTable, which will then reflect in the Datagrid automatically.