从DataGridView和SQL Server数据库中删除一行

时间:2015-10-01 03:31:50

标签: c# sql-server datagridview

我正在尝试删除DataGridView和SQL Server数据库中的一行数据。在第一次单击删除按钮时,它显示

MessageBox.Show("Record Deleted Successfully!");

但未在DataGridView和数据库中删除所选行。

这是我的代码:

private void PayratesDisplay()
{
    con.Open();

    DataTable dt = new DataTable();
    adap = new SqlDataAdapter("select Membership AS [Membership Type], PerSession AS [Per Session], Discounted from tbl_payrates", con);

    adap.Fill(dt);

    dataGridView4.DataSource = dt;

    con.Close();
}

// Clear Data  
private void ClearData()
{
    tbMemship.Text = "";
    tbPerses.Text = "";
    tbDisc.Text = "";
    ID = 0;
}

private void btn_PRdel_Click(object sender, EventArgs e)
{
    if (ID != 0)
    {
        con.Open();

        cmd = new SqlCommand("DELETE FROM tbl_payrates WHERE Membership = @Membership", con);
        cmd.Parameters.AddWithValue("@Membership", ID);

        cmd.ExecuteNonQuery();

        con.Close();

        MessageBox.Show("Record Deleted Successfully!");

        PayratesDisplay();
        ClearData();
    }
}  

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您正在尝试删除网格的当前行。然后不需要ID成员,你可以使用这样的东西

private void btn_PRdel_Click(object sender, EventArgs e)
{
    var row = dataGridView4.CurrentRow;
    if (row == null) return;
    var ID = row.Cells["Membership Type"].Value;
    // The rest of the code (w/o the "if ID != 0")
}

答案 1 :(得分:0)

像这样更改你的代码

int r=cmd.ExecuteNonQuery();
con.Close();
if(r>0){MessageBox.Show("Record Deleted Successfully!");}