在窗体load
事件里面设置表格dataGridView的AutoGenerateColumns
为 false
dataGridView.AutoGenerateColumns = false
调用方法ClearSelection
dataGridView.ClearSelection()
设置DefaultCellStyle
里面的WarapMode
属性为 true
设置属性 AutoSizeRowMode
为 DisplayedCellsExceptHeaders
设置方法AutoResizeColumns
dataGridView.AutoSizeRowsMode=DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
dataGridView.AutoResizeColumns();
表格RowPostPaint
事件
private void dataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
//获取行对象
var row = dataGridView.Rows[e.RowIndex];
//对行的第一列value赋值
row.Cells[0].Value = row.Index + 1;
}
表格RowPostPaint
事件绘制图片或者数字
private void dataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
//读取要显示的图片
Image img = Properties.Resources.img
//绘制图标,图标绘制的坐标位置可自己调节
e.Graphics.DrawImage(img, e.RowBounds.Left + dataGridView.RowHeadersWidth - 40, e.RowBounds.Top + 4, 16, 16);
}
在表格的CellFormatting
事件里面进行转换操作,比如一个状态字段是int类型,显示需要转换成对应的字符串显示。
private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//转换第一列
if (e.ColumnIndex == 0)
{
//取得行
var row = dataGridView.Rows[e.RowIndex];
//取得列值,如果是绑定的数据,可以将row.DataBoundItem转换成绑定对象再取值判断
var cell=row.cell[0].value.ToString();
string grad = "";
if cell == "1")
grad = "A";
else if (cell == "2")
grad = "B";
else if (cell == "3")
grad = "C";
else if (cell == "4")
grad = "D";
else if (cell == "5")
grad = "E";
e.Value = grad;
}
}
在表格的CellMouseDown
事件里面设置选中行
private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right && e.RowIndex > -1 && e.ColumnIndex > -1)
{
dataGridView.CurrentRow.Selected = false;
dataGridView.Rows[e.RowIndex].Selected = true;
}
}
//dgvBook.SelectedRows[0].Index 为要刷新的行号
dataGridView.InvalidateRow(dgvBook.SelectedRows[0].Index);