C#编程-72:dataGridView删除行_彭世瑜_新浪博客

144 阅读1分钟
  1. using System;

  2. using System.Windows.Forms;

  3.  

  4. namespace DataGridViewContextMenuStrip

  5. {

  6.     public partial class Form1 : Form

  7.     {

  8.         public Form1()

  9.         {

  10.             InitializeComponent();

  11.         }

  12.  

  13.         private void Form1_Load(object sender, EventArgs e)

  14.         {

  15.             // TODO:  这行代码将数据加载到表“companyDataSet.clerk”中。您可以根据需要移动或删除它。

  16.             this.clerkTableAdapter.Fill(this.companyDataSet.clerk);

  17.  

  18.         }

  19.         private int rowIndex;

  20.         private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)

  21.         {

  22.             if (e.Button == MouseButtons.Right)

  23.             {

  24.                 rowIndex=e.RowIndex;

  25.                 this.dataGridView1.Rows[e.RowIndex].Selected = true;

  26.  

  27.                 this.dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[1];

  28.                 this.contextMenuStrip1.Show(dataGridView1, e.Location);

  29.                 this.contextMenuStrip1.Show(Cursor.Position);

  30.             }

  31.         }

  32.  

  33.         private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)

  34.         {

  35.             if (!this.dataGridView1.Rows[rowIndex].IsNewRow)

  36.             { 

  37.                 this.dataGridView1.Rows.RemoveAt(rowIndex);

  38.             }

  39.         }

  40.     }

  41. }