1) 行右键菜单
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]; } if (dataGridView1.CurrentRow != null) { int idx = dataGridView1.CurrentRow.Index; if (idx >= 0) { string isexport = mDataTableCun.Rows[idx]["ISEXPORT"].ToString(); if (isexport == "已导出") { //弹出操作菜单 contextMenuStrip1.Show(MousePosition.X, MousePosition.Y); } } } } } }
2) 行自动编号
private void dataGridView1_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) 单元格取值设值
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 2) { dataGridView1.EndEdit(); string ischeck = dataGridView1.Rows[e.RowIndex].Cells["visible"].Value.ToString(); if (ischeck == "0") { dataGridView1.Rows[e.RowIndex].Cells["edit"].Value = "0"; } } }