- FullRowSelect 狀態下且啟用刪除,按 Delete 鍵
- 透過 ContextMenuStrip 來進行刪除
Layout
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.AutoGenerateColumns = false;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
{
DataPropertyName = "ID",
Name = "ColID",
HeaderText = "流水號",
Width = 100,
Visible = true,
SortMode = DataGridViewColumnSortMode.Automatic
});
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
{
DataPropertyName = "ProdName",
Name = "ColProdName",
HeaderText = "產品名稱",
Width = 100,
Visible = true,
SortMode = DataGridViewColumnSortMode.Automatic
});
dataGridView1.DataSource = GetDataSource();
dataGridView1.MouseDown += DataGridView1_MouseDown;
dataGridView1.UserDeletingRow += DataGridView1_UserDeletingRow;
}
private void DataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
DialogResult result =
MessageBox.Show(
"是否刪除該筆資料",
"確認",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (result == DialogResult.No) e.Cancel = true;
}
private void DataGridView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Right) return;
DataGridView dgv = sender as DataGridView;
ShowMenu(dgv, e);
}
private void ShowMenu(DataGridView dgv, MouseEventArgs args)
{
// 取得 RowIndex
// 方法 1:透過 HitTest()
int RowIndex = dgv.HitTest(args.X, args.Y).RowIndex;
// 方法 2:CurrentRow
int RowIndex = dgv.CurrentRow.Index;
if (RowIndex < 0) return;
ContextMenuStrip menu = new ContextMenuStrip();
ToolStripMenuItem item = new ToolStripMenuItem("删除該筆資料");
item.Click += (sender, e) =>
{
dgv.Rows.RemoveAt(RowIndex);
};
menu.Items.Add(item);
// 四種指定 ContextMenuStrip 位置方式
// 方法 1
menu.Show(dgv, new Point(e.X, e.Y));
// 方法 2
menu.Show(dgv, e.Location);
// 方法 3
menu.Show(Cursor.Position);
// 方法 4:DataGridView 也有 PointToClient() 可以使用
menu.Show(dgv, dgv.PointToClient(Cursor.Position));
}
private DataTable GetDataSource()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("ProdName", typeof(string));
dt.Rows.Add(1, "SQL Server 2016");
dt.Rows.Add(2, "SQL Server 2014");
dt.Rows.Add(3, "SQL Server 2012");
dt.Rows.Add(4, "SQL Server 2008");
dt.Rows.Add(5, "SQL Server 2005");
return dt;
}
}
}
利用 ContextMenuStrip 刪除資料利用 Delete 鍵刪除資料
DataGridView 必須為 FullRowSelect 狀態下且啟用刪除才會觸發
實際執行
- 參考資料
- C#:使用快捷菜单(ContextMenuStrip)删除DataGridView控件指定行-MouseClick
- Delete row from datagridview by right click-CellMouseUp
- BS 討論
- DataGridView.HitTest 方法
- StackOverFlow 討論 - MouseEventArgs 和 DataGridViewCellMouseEventArgs Location 討論
沒有留言:
張貼留言