分享

DataGridView右键删除行

 山泉的往事 2017-07-12

插入右键控件(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
            }
        }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多