删除网格中的单行

时间:2013-07-02 06:18:48

标签: asp.net sql-server c#-4.0

我需要从网格中删除一行,但每次单击网格中的删除按钮时,我的整个数据库都会被删除。请帮我纠正我的代码谢谢。

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
    gridbind();
    con.Open();
    SqlCommand cmd = new SqlCommand ("delete from registration where Id=" + lblid.Text + "", con);
    cmd.ExecuteNonQuery();
    con.Close();
}

和gridbind函数是:

private void gridbind()
{

    string sql = string.Empty;
    string id = this.txtid.Text;
    string gender = this.DropDownList1.SelectedValue;

    if (gender =="male" || gender == "female") 
        sql = "Select * from registration WHERE Id like '%" + id + "%' AND gender = '"+gender+"'";

    if (gender =="male" || gender == "female" && id == this.txtid.Text)
        sql = " Select * from registration Where Id like '%" + id + "%' ";

    if (gender == "all" && id == this.txtid.Text)
        sql = " Select * from registration Where Id like '%" + id + "%' ";

    SqlCommand cmd = new SqlCommand(sql, con);

    cmd.Parameters.AddWithValue("@id",id);
    cmd.Parameters.AddWithValue("@gender", gender);

    con.Open();

    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();

    da.Fill(ds);

    GridView1.DataSource = ds;
    GridView1.DataBind();

    con.Close();
}

1 个答案:

答案 0 :(得分:0)

首先,您必须对名为“lblid”的行标签使用findcontrol。

第二,最后绑定。

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
    Label theGridRowLabel = (Label)row.FindControl("lblid");

    con.Open();
    SqlCommand cmd = 
           new SqlCommand ("delete from registration where Id=" + theGridRowLabel.Text, con);
    cmd.ExecuteNonQuery();
    con.Close();

    gridbind();
}