首都产业建设集团网站,wordpress数据库导出工具,沧州做网站的公司排名,信阳做网站 汉狮网络前些天在写个小程序#xff0c;用到DataGridView#xff0c;想给它动态的显示行号。不是很费劲GOOGLE了一下#xff0c;这GOOGLE不要紧#xff0c;发现了不少问题。以下基本上都是GOOGLE搜索出来的网上的一些解决方法#xff0c;千篇一律都是这样的#xff1a;private vo…前些天在写个小程序用到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~