JIALIH_H 2018-11-01 03:20 采纳率: 50%
浏览 2624
已采纳

c#winform中datagridview删除数据库中的整行数据

图片说明
int id = 0;
try
{
id = (int)dgv_inventory.CurrentRow.Cells[0].Value;
}
catch (System.Exception ex)
{
MessageBox.Show("请选择有效数据行!");
return;
}
if (MessageBox.Show("确定要删除吗?", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
return;
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString =
"Server=(local);Database=DB_Equipment;Integrated Security=sspi";
using (SqlConnection conn = new SqlConnection(sqlConnection.ConnectionString))
{
string sql = string.Format("delete from tb_inventory where EquipmentNo={0}", id);
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
int n = Convert.ToInt32(cmd.ExecuteNonQuery());
if (n != 1)
{
MessageBox.Show("删除失败!");
}
else
{
MessageBox.Show("删除成功!");
}
}
以上为删除按钮事件中的代码,运行时只能运行到try_catch语句,即一直跳出窗体提示“请选择有效数据行”,这是哪里出现了问题?

  • 写回答

2条回答 默认 最新

  • 叫兽-郭老师 Java领域新星创作者 2018-11-01 03:23
    关注

    id = (int)dgv_inventory.CurrentRow.Cells[0].Value; 报错了,估计你dgv_inventory.CurrentRow.Cells[0].Value获取到的是空。你先用string类型接受下,debug看下结果是什么。转化成int时报错了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?