Winform Datagridview 添加右键菜单
#region 添加右键删除菜单
private void kryptonDataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
if (e.RowIndex >= 0)
{
if (kryptonDataGridView1.Rows[e.RowIndex].Selected == false)
{
kryptonDataGridView1.ClearSelection();
kryptonDataGridView1.Rows[e.RowIndex].Selected = true;
}
if (kryptonDataGridView1.SelectedRows.Count == 1 && e.ColumnIndex != -1)
{
kryptonDataGridView1.CurrentCell = kryptonDataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
}
_ShowMenu(kryptonDataGridView1, kryptonContextMenu1);
}
}
}
private void _ShowMenu(Control c, KryptonContextMenu kmenu)
{
kmenu.Show(c.RectangleToScreen(c.ClientRectangle), (KryptonContextMenuPositionH)Enum.Parse(typeof(KryptonContextMenuPositionH), "Left"), (KryptonContextMenuPositionV)Enum.Parse(typeof(KryptonContextMenuPositionV), "Below"));
}
private void kryptonContextMenuItem1_Click(object sender, EventArgs e)
{
object obId = kryptonDataGridView1.CurrentRow.Cells["Id"].Value;
if (obId == null || DBNull.Value.Equals(obId))
{
KryptonMessageBox.Show("你选择的是空行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
return;
}
else
{
if (KryptonMessageBox.Show("确定删除?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
//获得选择数据
StockDetail sd = this.cbgll.GetStockDetailById(obId.ToString());
if (sd != null)
{
//是否已经审核
if (sd.Cid.State == 0)
{
new StockDetailDAL().Remove(sd);
//删除控件行
kryptonDataGridView1.Rows.Remove(kryptonDataGridView1.CurrentRow);
}
else
{
KryptonMessageBox.Show("已审核不能删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
else
{
//删除控件行
kryptonDataGridView1.Rows.Remove(kryptonDataGridView1.CurrentRow);
}
}
}
}
#endregion