前些天在写个小程序,用到DataGridView,想给它动态的显示行号。不是很费劲GOOGLE了一下,这GOOGLE不要紧,发现了不少问题。以下基本上都是GOOGLE搜索出来的网上的一些解决方法,千篇一律都是这样的:
private void DataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
for (int i = 0; i < e.RowCount; i++)
{
this.dgvKBRollUp.Rows[e.RowIndex + i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
this.dgvKBRollUp.Rows[e.RowIndex + i].HeaderCell.Value = (e.RowIndex + i + 1).ToString();
}
for (int i = e.RowIndex + e.RowCount; i < this.dgvKBRollUp.Rows.Count; i++)
{
this.dgvKBRollUp.Rows[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
this.dgvKBRollUp.Rows[i].HeaderCell.Value = (i + 1).ToString();
}
}
private void DataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
for (int i = 0; i < e.RowCount; i++)
{
this.dgvKBRollUp.Rows[e.RowIndex + i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
this.dgvKBRollUp.Rows[e.RowIndex + i].HeaderCell.Value = (e.RowIndex + i + 1).ToString();
}
for (int i = e.RowIndex + e.RowCount; i < this.dgvKBRollUp.Rows.Count; i++)
{
this.dgvKBRollUp.Rows[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
this.dgvKBRollUp.Rows[i].HeaderCell.Value = (i + 1).ToString();
}
}
只要用过这段代码的人就应该发现这段代码是运行出错的。原因就出在RowsRemoved事件里,会抛出一个Index outof range的异常。然而就是这么一段有错的代码,几乎充斥着整个互联网,千篇一律的COPY,没有一个人纠正。
先说下这段代码出错的原因吧:
在RowsRemoved事件里,最开始生成DataGridView的数据的时候,也是会触发这个事件的。这个时候DataGridView控件的Rows.Count就是0。那下面这行代码就有问题了:
this.dgvKBRollUp.Rows[e.RowIndex + i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
e.RowIndex + i,这里对应的是Rows[0],但是Rows.Count还是0啊,Rows[0]是不存在的。要存在Rows[0]起码DataGridView控件要有一行才行。为了避免这个错误,小小的修改代码就行了:
private void dgvKBRollUp_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
if (dgvKBRollUp.Rows.Count != 0)
{
for (int i = 0; i < e.RowCount; i++)
{
this.dgvKBRollUp.Rows[e.RowIndex + i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
this.dgvKBRollUp.Rows[e.RowIndex + i].HeaderCell.Value = (e.RowIndex + i + 1).ToString();
}
for (int i = e.RowIndex + e.RowCount; i < this.dgvKBRollUp.Rows.Count; i++)
{
this.dgvKBRollUp.Rows[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
this.dgvKBRollUp.Rows[i].HeaderCell.Value = (i + 1).ToString();
}
}
只要加上一个对Rows.Count的判断就可以避免这个错误。希望网上的一些COPY的朋友也要注意了,以后COPY过来的时候,自己还是要动手验证一下。将一个错误的信息胡乱的传播是对一些新手以及自己都不怎么好的。最后附上微软MSDN里面关于e.RowIndex和e.RowCount的一段代码:
System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder();
messageBoxCS.AppendFormat("{0} = {1}", "RowIndex", e.RowIndex);
messageBoxCS.AppendLine();
messageBoxCS.AppendFormat("{0} = {1}", "RowCount", e.RowCount);
messageBoxCS.AppendLine();
MessageBox.Show(messageBoxCS.ToString(), "RowsRemoved Event");
通过这段代码你可以很轻松地跟踪事件参数里的e.RowIndex和e.RowCount的值。当然你可以DEBUG,一样的。我就是DEBUG的O(∩_∩)O~