winform datagridview 通过右键菜单来删除数据行



1.实现当鼠标移到数据行时,右键删除数据。

 步骤1.先定义变量CurrentRowIndex来存储鼠标经过的行数。

如下:

View Code
1   public partial class FormTest : Form
2     {
3         private bool isLoad { getset; }
4         /// <summary>
5         /// 当前行号
6         /// </summary>
7         private int CurrentRowIndex { getset; }

 

 2.为该变量赋值。使用CellMouseEnter

代码如下:

 

View Code
1 private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
2         {
3             var dgv = (DataGridView)sender;
4             CurrentRowIndex = e.RowIndex;
5             CurrentColumnIndex = e.ColumnIndex;
6             
7         }

 

 3.右键鼠标,然后点击删除,

代码如下:

View Code
1  private void removeToolStripMenuItem_Click(object sender, EventArgs e)
2         {
3            // DataGridViewRowCollection rowCollection = new DataGridViewRowCollection(dataGridView1);
4             DataGridViewRow row = dataGridView1.Rows[CurrentRowIndex];
5           dataGridView1.Rows.Remove(row);
6             //防止滚动条滚到不是想要到的地方。
7           dataGridView1.CurrentCell = dataGridView1[0, CurrentRowIndex];
8             
9         }

 

4.删除行是的条件判断 处理。

4.1当按下del键时,执行如下函数

  

View Code
 1   private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
 2         {
 3             // 删除前的用户确认。
 4             if (MessageBox.Show("确认要删除该行数据吗?""删除确认",
 5                 MessageBoxButtons.OKCancel,
 6                 MessageBoxIcon.Question,
 7                 MessageBoxDefaultButton.Button2) != DialogResult.OK)
 8             {
 9                 // 如果不是 OK,则取消。
10                 e.Cancel = true;
11             }
12         }

 

 4.2若按鼠标右键删除时,可执行如下函数。

 

View Code
 1  private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
 2         {
 3             if (!isLoad)
 4             {
 5                 if (MessageBox.Show(
 6                     "确定要删除数据吗?",
 7                     "删除确认",
 8                     MessageBoxButtons.OKCancel, 
 9                     MessageBoxIcon.Question, 
10                     MessageBoxDefaultButton.Button2) == DialogResult.OK
11                     )
12                 {
13                     int removeIndex = e.RowIndex;
14                     //     string removeColumnOneText = Convert.ToString(dataGridView1[0,e.RowIndex].Value);
15                     MessageBox.Show("你的数据被删除了:" + removeIndex);
16                 }
17                
18             }
19          
20         }

 

 

 

 

 

 

 

 

 

 

 

posted on 2011-09-06 00:02  wtq  阅读(8001)  评论(0编辑  收藏  举报