【问题标题】:SQL Delete Statement does not work with selecting a row from a dataGridViewSQL Delete 语句不适用于从 dataGridView 中选择行
【发布时间】:2016-04-03 11:44:17
【问题描述】:

我正在尝试从链接到数据库中的表的 DataGridView 中删除选定的行。它说明了以下错误代码。

关于我在哪里出错的任何想法?

删除按钮代码

private void DeleteExtraBtn_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
    con.Open();
    try
    {
        //Delete selected extra row    
        SqlCommand sda = new SqlCommand("Delete From Extra Where Extra_ID = @Extra_ID", con);
        sda.Parameters.AddWithValue("@ExtraID", extraGridView.CurrentRow.Cells[0]);
        sda.ExecuteNonQuery(); 

    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }


    con.Close();
    loadExtraTable();
}

【问题讨论】:

    标签: c# mysql datagridview


    【解决方案1】:

    我没有看到你在任何地方执行命令。

    添加;

    sda.ExecuteNonQuery();
    

    您还引用了单元格对象而不是它的值。 另外,您引用@ExtraID@Extra_ID

    private void DeleteExtraBtn_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
        con.Open();
        try
        {
            //Delete selected extra row    
            SqlCommand sda = new SqlCommand("Delete From Extra Where Extra_ID = @ExtraID", con);
            sda.Parameters.AddWithValue("@ExtraID", extraGridView.CurrentRow.Cells[0].Value);
            sda.ExecuteNonQuery();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    
    
        con.Close();
        loadExtraTable();
    }
    

    【讨论】:

    • 哦,是的,抱歉。我没有将它包含在上面的示例中。但它仍然无法解决这个问题。
    • 为了更好的实践,您应该将连接和命令包装在使用块中,以便于清理。你检查过骗局正在打开吗?如果它没有打开,它不会总是抛出错误。
    • 显示我刚刚添加到上面代码中的错误。
    • 看起来您可能正在尝试添加单元格对象而不是单元格对象值,应该看起来更接近 extraGridView.CurrentRow.Cells[0].ValueextraGridView.CurrentRow.Cells[0].Text
    • 你有一个变量命名不匹配 @Extra_ID != @ExtraID
    【解决方案2】:

    什么是“ExtraId”,一个文本框,一个字符串?

    根据情况,你必须使用:

    SqlCommand sda = new SqlCommand("Delete From Extra Where Extra_ID = @" + Extra_ID.Text, con);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-07
      • 2013-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多