Note that there are some explanatory texts on larger screens.

plurals
  1. POAdding rows to DataGridView programmatically
    text
    copied!<p>I have a <code>DatGridView</code> 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. </p> <p>When a new row is created, the <code>DataGridViewImageCell</code> from the first column is added to the custom class that keeps track of the completed fields. </p> <p>Here is the code to add a new row:</p> <pre><code>//initiate the new row object[] buffer = new object[13]; buffer[0] = nullImage; //a blank image for (int i = 1; i &lt; buffer.Length; i++) { buffer[i] = String.Empty; } rowID = DataGridView1.Rows.Add(buffer); </code></pre> <p>Here is the <code>RowAdded</code> code:</p> <pre><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 } </code></pre> <p>The custom class contains a List of <code>DataGridViewImageCells</code> dgvic; here is its' <code>AddRow</code> method:</p> <pre><code> private List&lt;object&gt; dgvic = new List&lt;object&gt;(); public void AddRow(DataGridViewImageCell p) { items.Add(new List&lt;int&gt;());//List of ints to keep track of completed fields dgvic.Add(p); } </code></pre> <p>When I enter the debugger (while adding rows programmatically) I can see that each time I add a new row the <code>DataGridViewImageCells</code> stored in <code>dgvic</code> are all from the most recent row. For instance after adding 3 rows, I'd expect the 3 <code>DataGridViewImageCells</code> to be from rows 0, 1 and 2; however all of them are from row 2. </p> <p>It looks to me that <code>RowCount</code> is still tied to each <code>DataGridViewCell</code>, and as <code>RowCount</code> increments the cell changes. If this were the case though, how come it works through the GUI? Does anyone have any ideas?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload