简体   繁体   中英

Adding rows to DataGridView programmatically

I have a DatGridView to which I add new rows. The first column of every row is an image the indicates whether the rest of the row has been completed. To keep track of this each row has a List-like object attached to it that counts the number of completed fields, then changes the image if enough fields have been completed. This works exactly as expected when the user is adding rows in the GUI, however I run into problems when I try to add new rows programmatically.

When a new row is created, the DataGridViewImageCell from the first column is added to the custom class that keeps track of the completed fields.

Here is the code to add a new row:

//initiate the new row
object[] buffer = new object[13];
buffer[0] = nullImage; //a blank image

for (int i = 1; i < buffer.Length; i++)
{
     buffer[i] = String.Empty;
}

rowID = DataGridView1.Rows.Add(buffer);

Here is the RowAdded code:

    private void DataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
    {
        DataGridViewImageCell tmp = (DataGridViewImageCell)DataGridView1.Rows[DataGridView1.RowCount - 1].Cells[0];
        DataGridView1ValidateFields.AddRow(tmp); //custom class to keep track of completed fields
    }

The custom class contains a List of DataGridViewImageCells dgvic; here is its' AddRow method:

    private List<object> dgvic = new List<object>();
    public void AddRow(DataGridViewImageCell p)
    {
        items.Add(new List<int>());//List of ints to keep track of completed fields
        dgvic.Add(p);
    }

When I enter the debugger (while adding rows programmatically) I can see that each time I add a new row the DataGridViewImageCells stored in dgvic are all from the most recent row. For instance after adding 3 rows, I'd expect the 3 DataGridViewImageCells to be from rows 0, 1 and 2; however all of them are from row 2.

It looks to me that RowCount is still tied to each DataGridViewCell , and as RowCount increments the cell changes. If this were the case though, how come it works through the GUI? Does anyone have any ideas?

Change yours AddedRows event as follows:

private void DataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    int index = e.RowIndex;
    for (int i = 0; i < e.RowCount; i++)
    {
        DataGridViewImageCell tmp = (DataGridViewImageCell)DataGridView1.Rows[index].Cells[0];
        DataGridView1ValidateFields.AddRow(tmp);
        index++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM