一.DataGridView列右击菜单事件处理
(1). 添加一个快捷菜单contextMenuStrip1;
(2). 给dataGridView1的CellMouseDown事件添加处理程序:
private void DataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
if (e.RowIndex >= 0)
{
//若行已是选中状态就不再进行设置
if (dataGridView1.Rows[e.RowIndex].Selected == false)
{
dataGridView1.ClearSelection();
dataGridView1.Rows[e.RowIndex].Selected = true;
}
//只选中一行时设置活动单元格
if (dataGridView1.SelectedRows.Count == 1)
{
dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
}
//弹出操作菜单
contextMenuStrip1.Show(MousePosition.X, MousePosition.Y);
}
}
}
设置dataGridView1选中一行:将SelectionMode属性值改为FullRowSelect
二.dataGridView1的一些常用操作
//获取选中行(第0列)的值:
string Id = this.dataGridView1.SelectedCells[0].Value.ToString();
//获取选中行索引:
int rowindex = dataGridView1.CurrentRow.Index;
//dataGridView1自动调整列距
this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
//虚拟模式
this.dataGridView1.VirtualMode = true;
//设置第0列不显示
this.dataGridView1.Columns[0].Visible = false;
//设置第0行颜色
this.dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Green; //在第0列后新增一列TextBoxColumn
DataGridViewTextBoxColumn newColumn = new DataGridViewTextBoxColumn();
this.dataGridView1.Columns.Insert(0, newColumn);