插入右键控件(ConTextMenuStrip)
private int index = 0;
private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
this.dataGridView1.Rows[e.RowIndex].Selected = true;//是否选中当前行
index = e.RowIndex;
this.dataGridView1.CurrentCell = this.dataGridView1.Rows[e.RowIndex].Cells[0];
//每次选中行都刷新到datagridview中的活动单元格
this.contextMenuStrip1.Show(this.dataGridView1, e.Location);
//指定控件(DataGridView),指定位置(鼠标指定位置)
this.contextMenuStrip1.Show(Cursor.Position);//锁定右键列表出现的位置
}
}
private void 删除行ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!this.dataGridView1.Rows[index].IsNewRow)//判断是否为新行
{
string deletestr = "delete Staff where Name = '"+this.dataGridView1.CurrentCell.Value+"'";
string dele = this.dataGridView1.CurrentCell.Value.ToString();
SQLShuJu sj = new SQLShuJu();
SqlConnection conn = sj.connect();
conn.Open();
SqlCommand comm = new SqlCommand(deletestr, conn);
comm.ExecuteNonQuery();
conn.Close();
this.dataGridView1.Rows.RemoveAt(index);//从集合中移除指定的行
MessageBox.Show("删除成功" + dele);
//必须数据库先删除后在刷新Ui界面的数据,因为CurrentCell会因为UI界面刷新删除数据后发生单元格的变动,
//跳到下一行数据,从而导致数据库删除失败。
//对于只删除一行的数据库,个人比较推荐Command
}
}
|