简体   繁体   中英

Deleting Checked rows from gridview

I'm trying to delete checked(Selected) rows from gridview , but selected row is not deleting. Why?

//Class-Method

public void DeleteDataRow(string ID)
{
    using (SqlCommand xComm = new SqlCommand())
    {
        Conn.Open();
        new SqlCommand("Delete from Costumers Where CID='" + ID + "' ", Conn);
        Conn.Close();
    }
}

//webform-Method

protected void xbutton_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in GV.Rows)
    {
        CheckBox C = row.Cells[0].FindControl("Check") as CheckBox;
        string  ID= row.Cells[1].Text;
        if(C.Checked)
        {
            m.DeleteDataRow(ID);
        }
    }

    GV.DataSource = m.Select();
    GV.DataBind();
}

Are there any error messages? Also where are you defining Conn , and is it accessible to DeleteDataRow() ?

If so, you'll need to define xComm a bit differently within your using statement.

After you open the connection, you need to execute the query in some matter such as using ExecuteNonQuery to fire the sql statement. See MSDN documentation

public void DeleteDataRow(string ID)
{
    using (SqlCommand xComm = new SqlCommand("Delete from Customers Where CID='" + ID + "' ", Conn))
    {
        Conn.Open();
        int result = xComm.ExecuteNonQuery();
        Conn.Close();
    }
}

Another thing to note is that you may want to check the spelling of Customers in your query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM