//设置列宽
this.GridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
this.GridView1.Columns[0].Width = 200;
this.GridView1.Columns[1].Width = 200;
//设置字段行
this.GridView1.Columns[0].HeaderCell.Value = "编号";
this.GridView1.Columns[1].HeaderCell.Value = "时间";
//内容居中显示
GridView1.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
//行头居中显示
DataGridViewCellStyle headerStyle = new DataGridViewCellStyle();
headerStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.GridView1.ColumnHeadersDefaultCellStyle = headerStyle;
//设置时间字段内容包含秒
GridView1.Columns[2].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
GridView1.Columns[3].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
表格最左侧加序号用
1.在datagridview的属性中找到RowHeaderVisible并将其属性值更改为True,即可在datagridview最左侧看到增加一列。
2.在form中添加代码
private void dgv_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
e.RowBounds.Location.Y,
dataGridView1.RowHeadersWidth - 4,
e.RowBounds.Height);
TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
dataGridView1.RowHeadersDefaultCellStyle.Font,
rectangle,
dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
}
3.在form.Designer.cs中增加
this.dataGridView1.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dgv_RowPostPaint);