隱藏空白列:
[csharp]
dataGridView1.RowHeadersVisible = false;
dataGridView1.RowHeadersVisible = false;
設置空白列的寬度不可改變:
[csharp]
this.dgv.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing;
this.dgv.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing;
在空白列顯示行數的方法:
[csharp]
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
}
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建議使得如下方法:
[csharp]
//實現功能 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