我正在尝试通过代码隐藏文件更新Gridview。 点击更新按钮,我得到“关键字集附近的语法不正确 tableName正确显示
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label l=GridView1.Rows[e.RowIndex].FindControl("ID") as Label;
TextBox question=GridView1.Rows[e.RowIndex].FindControl("questions") as TextBox;
TextBox answer=GridView1.Rows[e.RowIndex].FindControl("answer") as TextBox;
TextBox option1=GridView1.Rows[e.RowIndex].FindControl("op1") as TextBox;
TextBox option2=GridView1.Rows[e.RowIndex].FindControl("op2") as TextBox;
TextBox option3=GridView1.Rows[e.RowIndex].FindControl("op3") as TextBox;
TextBox option4=GridView1.Rows[e.RowIndex].FindControl("op4") as TextBox;
SqlDataSource1.UpdateCommand = "update " + tableName + " set [questions]='" + question.Text + "',[answer]='" + answer.Text + "',[op1]='" + option1.Text + "',[op2]='" + option2.Text+"',[op3]='"+option3.Text+"',[op4]='"+option4.Text+"' where ID="+l.Text;
//GridView1.DataBind();
}
我在Page_Load事件处理程序
中初始化了tableName
变量
if (!IsPostBack)
{
ch_id = Convert.ToInt32(Request.QueryString["ch_id"].ToString());
c_id = Convert.ToInt32(Session["course_id"]);
if (c_id == 1)
{
SqlDataSource1.SelectParameters["query"].DefaultValue = "select * from J2EE_testMaster where chapter_id=" + ch_id;
tableName = "J2EE_testMaster";
}
}
答案 0 :(得分:1)
根据您的评论,这是Page_Load
方法的样子:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ch_id = Convert.ToInt32(Request.QueryString["ch_id"].ToString());
c_id = Convert.ToInt32(Session["course_id"]);
if (c_id == 1)
{
SqlDataSource1.SelectParameters["query"].DefaultValue = "select * from J2EE_testMaster where chapter_id=" + ch_id;
tableName = "J2EE_testMaster";
}
}
}
执行tableName
时,这会使GridView1_RowUpdating
为空,因此SqlDataSource1.UpdateCommand
的值将变为update set [questions]=...
而不是update J2EE_testMaster set [questions]=...
。您需要在tableName
块之外设置if (!IsPostBack)
值:
protected void Page_Load(object sender, EventArgs e)
{
c_id = Convert.ToInt32(Session["course_id"]);
if (c_id == 1)
{
tableName = "J2EE_testMaster";
}
if (!IsPostBack)
{
ch_id = Convert.ToInt32(Request.QueryString["ch_id"].ToString());
if (c_id == 1)
{
SqlDataSource1.SelectParameters["query"].DefaultValue = "select * from J2EE_testMaster where chapter_id=" + ch_id;
}
}
}
您还需要参数化SQL查询以避免SQL Injection。