现在的位置: 首页 > 综合 > 正文

在DataGridView中添加行号

2018年01月27日 ⁄ 综合 ⁄ 共 1006字 ⁄ 字号 评论关闭

//from:http://www.codesky.net/club/showtopic.asp?id=1440

今天用C#2.0开发一个WinForm项目时,碰到一个在DataGridView中加行号的问题,找了一些资料,终于搞定。现把它贴出来供大家参考。
/+ZyDh(@ - 创中国最大的程序员交流社区  参考:http://community.csdn.net/Expert/topic/4671/4671416.xml?temp=.1845667程序员开发论坛#Y0CW;R0AO        U
        这里提到了两种方法:
        一、在数据加载后,用下面的代码:
   for (int i = 0; i < MyDataGridView.Rows.Count; i++)
            {
                int j = i + 1;
                MyDataGridView.Rows[i].HeaderCell.Value = j.ToString();
               
          }
这样当窗体第一次加载显示时,行号不会出现,于是试了第二种方法,加上自己改了一点。
二、在DataGridView的RowPostPaint事件中加入下面的代码:

  private void MyDataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
           SolidBrush B = new SolidBrush(Color.Red);
        //or:
           //SolidBrush b = new SolidBrush(this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor);
            e.Graphics.DrawString(Convert.ToString(e.RowIndex + 1, System.Globalization.CultureInfo.CurrentUICulture),
            e.InheritedRowStyle.Font, B,
            e.RowBounds.Location.X + 20,
            e.RowBounds.Location.Y + 4);
            //or:e.Graphics.
       }

抱歉!评论已关闭.