【问题】
已经可以自动向DataGridView添加数据,增加新行了。
但是想要给每行的行首,自动添加上对应的行号。
【解决过程】
1.参考:
Show row number in row header of a DataGridView
去试试:
初始化:
dgvSearchResult.CurrentRow.HeaderCell.Value = String.Format("{0}", dgvSearchResult.CurrentRow.Index + 1);
每次更新时:
dgvSearchResult.Rows.Add( singleGigInfo.title, singleGigInfo.sellerRating, singleGigInfo.estimatedDelivery, singleGigInfo.gigRating, singleGigInfo.ordersInQueue, singleGigInfo.sellerLevel, singleGigInfo.hasVideo, singleGigInfo.isExpressGig, singleGigInfo.coutryFlag, singleGigInfo.positiveReviews, singleGigInfo.negativeReviews, singleGigInfo.isTopRatedSeller, singleGigInfo.gigUrl); dgvSearchResult.Rows[dgvSearchResult.Rows.Count - 1].Selected = true; dgvSearchResult.FirstDisplayedScrollingRowIndex = dgvSearchResult.Rows.Count - 1; dgvSearchResult.Rows[dgvSearchResult.Rows.Count - 1].HeaderCell.Value = String.Format("{0}", dgvSearchResult.Rows[dgvSearchResult.Rows.Count - 1].Index + 1);
看看如何。
结果是可以显示出行号的,但是下次更新时,又消失了:
2.参考:
How to number the rows of DataGridView?
去专门看了看:
RowPostPaint事件
所以双击该事件,再去添加代码:
private void dgvSearchResult_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { dgvSearchResult.Rows[dgvSearchResult.Rows.Count - 1].HeaderCell.Value = String.Format("{0}", dgvSearchResult.Rows[dgvSearchResult.Rows.Count - 1].Index + 1); }
试试效果。
结果却始终刷新行号1:
3.再去参考:
auto generate row number to datagridview in windows application
干脆手动画每个行的行号吧:
for (int count = 0; (count <= (dgvSearchResult.Rows.Count - 2)); count++) { dgvSearchResult.Rows[count].HeaderCell.Value = String.Format("{0}", count + 1); //dgvSearchResult.Rows[count].HeaderCell.Value = string.Format((count + 1).ToString(), "0"); }
然后就可以了:
注意:
其中默认显示宽度不够宽,导致超过10以上的,都看到的只是整数部分:
需要自己手动拉宽显示宽度,即可。。。。
这点,还是很假,很悲催的。。。
刚才让我误以为string的format有问题,只能显示一位呢。。。
【总结】
还是没有系统自动支持去显示行号的。。。
还是需要在添加新行后,手动去画每个HeaderCell才可以的。
关于Row的Header部分的自动对齐,详见:
【已解决】设置C#的DataGridView中的行首的对齐方式
转载请注明:在路上 » 【已解决】C#的DataGridView中自动在行首添加行号