删除dataGridview中选中的一行或多行

一、实现的功能:可以删除一行或者多行数据,并在删除前提醒是否确定进行删除!

DialogResult RSS = MessageBox.Show(this,"确定要删除选中行数据码?","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
switch(RSS)
{
case DialogResult.Yes:
for (int i = this.dataGridView1.SelectedRows.Count; i > 0; i--)
{
int ID = Convert.ToInt32(dataGridView1.SelectedRows[i - 1].Cells[0].Value);
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[i - 1].Index);
//使用获得的ID删除数据库的数据
string SQL = "delete from UserInfo where UserId='"+ID.ToString()+"'";
int s =Convert.ToInt32(cl.Execute(SQL)); //cl是操作类的一个对像,Execute()是类中的一个方法
if (s!=0)
{
MessageBox.Show("成功删除选中行数据!");
}
}
break;
case DialogResult.No:
break;
}

 

public int Execute(string SQL)
{
SqlConnection conn = new SqlConnection(GetConn());
SqlCommand cmd = new SqlCommand(SQL, conn);
conn.Open();
int i =Convert.ToInt32(cmd.ExecuteNonQuery());
return i;
}

 

二:获取dataGridview中选中行

this.dataGridView1.SelectedCells[0].Value.ToString();

posted @ 2016-05-15 10:39  C#winform软件设计  阅读(17657)  评论(1编辑  收藏  举报