C# dataGridView空白列的设置

来源:互联网 发布:光通讯网络交换机 编辑:程序博客网 时间:2024/06/05 16:49

隐藏空白列:

dataGridView1.RowHeadersVisible = false;

设置空白列的宽度不可改变:

 this.dgv.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing;

在空白列显示行数的方法:

       private void dgv_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)        {            //#region 方法一            //using (SolidBrush b = new SolidBrush(dgv.RowHeadersDefaultCellStyle.ForeColor))            //{            //    int linen = 0;            //    linen = e.RowIndex + 1;            //    string line = linen.ToString();            //    e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);            //    SolidBrush B = new SolidBrush(Color.Red);            //}            //#endregion            #region 方法二            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgv.RowHeadersWidth - 4, e.RowBounds.Height);            TextRenderer.DrawText(                e.Graphics, (e.RowIndex + 1).ToString(),                dgv.RowHeadersDefaultCellStyle.Font,                rectangle,                dgv.RowHeadersDefaultCellStyle.ForeColor,                TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter                );            #endregion        }

如果你是使用Table绑定的Gridview建议使得如下方法:

  //实现功能  DataGridView  添加 自动编号               DataTable table =new DataTable();            DataColumn column = new DataColumn();            column.AutoIncrement = true;    //AutoIncrement  获取或设置一个值,该值指示对于添加到该表中的新行,列是否将列的值自动递增              column.ColumnName = "自动编号";            column.AutoIncrementSeed = 1;            column.AutoIncrementStep = 1;            table.Columns.Add(column);            table.Merge(table);//Merge合并DataTable              this.dataGridView1.DataSource = table;