最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】C#的DataGridView中自动在行首添加行号

C# crifan 8909浏览 0评论

【问题】

已经可以自动向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);

看看如何。

结果是可以显示出行号的,但是下次更新时,又消失了:

only show the lastest row number

2.参考:

How to number the rows of DataGridView?

去专门看了看:

RowPostPaint事件

RowPostPaint event

所以双击该事件,再去添加代码:

        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:

always refresh row number to 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");
            }

然后就可以了:

can show row number below 10

above 10 also can show for wider width

 

注意:

其中默认显示宽度不够宽,导致超过10以上的,都看到的只是整数部分:

above 10 not show completely

需要自己手动拉宽显示宽度,即可。。。。

这点,还是很假,很悲催的。。。

刚才让我误以为string的format有问题,只能显示一位呢。。。

 

【总结】

还是没有系统自动支持去显示行号的。。。

还是需要在添加新行后,手动去画每个HeaderCell才可以的。

 

关于Row的Header部分的自动对齐,详见:

【已解决】设置C#的DataGridView中的行首的对齐方式

转载请注明:在路上 » 【已解决】C#的DataGridView中自动在行首添加行号

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.148 seconds, using 22.13MB memory