如何删除DataGridView中选中的一行

 我来答
不西北慧的标1246
2017-07-31 · TA获得超过635个赞
知道小有建树答主
回答量:330
采纳率:0%
帮助的人:335万
展开全部
参考实例如下:
一、实现的功能:可以删除一行或者多行数据,并在删除前提醒是否确定进行删除。
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();
|评论
4 5
其他回答

注意datagridview绑定好数据先
//删除数据
private void button2_Click(object sender, EventArgs e)
{
try
{
int RowNumber;
if (null == dataGridView1.CurrentCell)
{
return;
}
RowNumber = dataGridView1.CurrentCell.RowIndex;
dataGridView1.Rows.RemoveAt(RowNumber);
if (null == sa)
{
MessageBox.Show("请先打开数据库");
return;
}
sa.Update((DataTable)bs.DataSource);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式