[WinForm]dataGridView自定动态设定序号列框

你可以在数据绑定或者行数有很大变化时测量一下DataGridView最大行数的行数的宽度然后在绘制代码如下


        SolidBrush solidBrush;
        StringFormat stringFormat = new StringFormat();
        private void Form36_Load(object sender, EventArgs e)
        {
            solidBrush = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor);
            stringFormat.Alignment = StringAlignment.Center;//垂直居中
            stringFormat.LineAlignment = StringAlignment.Center;//水平居中
            stringFormat.FormatFlags = StringFormatFlags.NoWrap;//不自动换行
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("AA");
            for (int i = 0; i < 111111; i++)
            {
                dataTable.Rows.Add(new object[] { i});
            }
            dataGridView1.DataSource = dataTable;
            SetRowHeadersWidth();//在数据源改变或者行数有很大变化时调用这个方法
        }

        private void SetRowHeadersWidth()
        {
            int line = dataGridView1.Rows.Count;
            Size size = TextRenderer.MeasureText(line.ToString(), dataGridView1.RowHeadersDefaultCellStyle.Font);//测试dataGridView1行数的宽度
            dataGridView1.RowHeadersWidth = size.Width + 30;//设置左侧行的宽度
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //在左侧行中间绘制
            e.Graphics.DrawString((e.RowIndex + 1).ToString(),
                e.InheritedRowStyle.Font,
                solidBrush,
                new Rectangle(e.RowBounds.X, e.RowBounds.Y, dataGridView1.RowHeadersWidth, e.RowBounds.Height),
                stringFormat);
        }



你可能感兴趣的:([WinForm]dataGridView自定动态设定序号列框)