DataGridView控件使用技巧
1、DataGridView右键菜单并选中该行
DataGridView中的CurrentRow属性为只读,且其Index也不能动态设置,只能在DataGridView中用左键来选择行,从而实现当前行的定位。
如果要在DataGridView中出现右键菜单并选中该行,可以用下面的代码:
private void dgvStudent_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)//判读是否是鼠标右键
{
dgvStudent.ClearSelection();
dgvStudent.Rows[e.RowIndex].Selected = true;
dgvStudent.CurrentCell = dgvStudent.Rows[e.RowIndex].Cells[e.ColumnIndex];
contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
}
}
2、DataGridView控件在最左边列显示序号
2.1 简单的方法:
绑定数据后,用下面的代码
int rowNumber = 1;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.HeaderCell.Value = rowNumber.ToString();
rowNumber++;
}
但序号是2位数的话,显示不清楚,列宽不够。要修改DataGridView控件的RowHeadersWidth属性。
2.2 第2种方法,能让箭头都不显示
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
Rectangle rowHeaderBounds = new Rectangle
(
2, e.RowBounds.Top,
this.dataGridView1.RowHeadersWidth - 2, e.RowBounds.Height - 1
);
using (Brush backbrush =
new SolidBrush(SystemColors.Control))
{
e.Graphics.FillRectangle(backbrush, rowHeaderBounds);
}
if (e.RowIndex >= dataGridView1.FirstDisplayedScrollingRowIndex)
{
using (SolidBrush b = new SolidBrush(dataGridView1.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);
}
}
}
}
3、修改DataGridView控件当前行数据后选中改行
private void dvClass_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
int index = dvClass.CurrentRow.Index;
int classId = Convert.ToInt32(dvClass.CurrentRow.Cells[0].Value);
FormClassEdit edit = new FormClassEdit(classId);
edit.ShowDialog();
GetClass();
dvClass.ClearSelection();
dvClass.Rows[index].Selected = true;
}