A few days ago, I was writing a mini program and used DataGridView to dynamically display the line number. It wasn't very difficult to GOOGLE for a while, it doesn't matter, I found a lot of problems. The following are basically some solutions found on the Internet by GOOGLE, and the same is true for this:
Copy the codeThe code is as follows:
private void DataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
for (int i = 0; i < ; i++)
{
[ + i]. = ;
[ + i]. = ( + i + 1).ToString();
}
for (int i = + ; i < ; i++)
{
[i]. = ;
[i]. = (i + 1).ToString();
}
}
private void DataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
for (int i = 0; i < ; i++)
{
[ + i]. = ;
[ + i]. = ( + i + 1).ToString();
}
for (int i = + ; i < ; i++)
{
[i]. = ;
[i]. = (i + 1).ToString();
}
}
Anyone who has used this code should find that this code is running incorrectly. The reason is that in the RowsRemoved event, an Index outof range exception will be thrown. However, this piece of wrong code almost fills the entire Internet, with the same COPY, and no one corrects it.
Let's talk about the reason for the error in this code:
In the RowsRemoved event, this event will also be triggered when the DataGridView data is first generated. At this time, the DataGridView control has 0. Then there is a problem with the following line of code:
Copy the codeThe code is as follows:
[ + i]. = ;
+ i, the corresponding Rows[0] here, but it is still 0, Rows[0] does not exist. To exist Rows[0], at least one line of the DataGridView control is required. To avoid this error, just modify the code slightly:
Copy the codeThe code is as follows:
private void dgvKBRollUp_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
if ( != 0)
{
for (int i = 0; i < ; i++)
{
[ + i]. = ;
[ + i]. = ( + i + 1).ToString();
}
for (int i = + ; i < ; i++)
{
[i]. = ;
[i]. = (i + 1).ToString();
}
}
Just add a correct judgment to avoid this error. I hope some COPY friends on the Internet should also pay attention. When COPY comes, you still have to verify it yourself. Spreading a wrong message randomly is not very good for some newbies and themselves.
Finally, a piece of code about and in Microsoft MSDN is attached:
Copy the codeThe code is as follows:
messageBoxCS = new ();
("{0} = {1}", "RowIndex", );
();
("{0} = {1}", "RowCount", );
();
((), "RowsRemoved Event");
With this code, you can easily track the sum values in event parameters. Of course you can DEBUG, the same. I am DEBUG'sO(∩_∩)O~