【发布时间】:2013-07-02 06:18:47
【问题描述】:
我需要从网格中删除一行,但是每次单击网格中的删除按钮时,我的整个数据库都会被删除。请帮我纠正我的代码谢谢。
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();
}
【问题讨论】:
-
lblid.Text 你在哪里设置这个文本?
-
为什么要绑定数据源并然后删除该行?
-
另外,你的 if 语句没有意义。
id == this.txtid.Text将始终评估为 true,因为 id 被初始化为string id = this.txtid.Text;。 -
在现实世界中,您必须在数据库中编写存储过程来执行此类任务,请清理您的代码并编写 Sp,然后在从代码中调用它们之前检查它们。这是一个如何从 c# 调用 Sp 的教程。看看这个。 csharp-station.com/Tutorial/AdoDotNet/Lesson07
标签: asp.net sql-server c#-4.0