【问题标题】:submit button and checkbox not updating sql server database [closed]提交按钮和复选框不更新 sql server 数据库[关闭]
【发布时间】:2013-08-23 18:14:36
【问题描述】:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DropDownList1.DataSource = (DataTable)Session["dt"];
            DropDownList1.DataValueField = "base";
            DropDownList1.DataTextField = "base";
            DropDownList1.DataBind();
        }
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {


    }

    string str;
    string email;
    string base1;

    protected void Submit_Click(object sender, EventArgs e)
    {
        if (CheckBox9.Checked == true)
        {
            str = str + CheckBox9.Text + 'x';
        }


    SqlConnection con = new SqlConnection(...);
    String sql = "UPDATE INQUIRY2 set Question1 = @str WHERE email = @email AND base = @base;";

    SqlCommand cmd = new SqlCommand(sql, con);
    con.Open();

    DataTable theDataTable = null;

       // Verify that dt is actually in session before trying to get it

        if(Session["dt"] != null)
        {
            theDataTable = Session["dt"] as DataTable;
        }



    //Verify that the data table is not null
    if(theDataTable != null)
    {
        email = theDataTable.Rows[0]["email"].ToString();
        base1 = theDataTable.Rows[0]["base"].ToString();
    }

    cmd.Parameters.AddWithValue("@email", email);
    cmd.Parameters.AddWithValue("@str", str);
    cmd.Parameters.AddWithValue("@base", base1);

    con.Close();  

    }

}

}

【问题讨论】:

  • 你忘了问问题。

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


【解决方案1】:

您缺少实际命令的执行调用:

cmd.Parameters.AddWithValue("@email", email);
cmd.Parameters.AddWithValue("@str", str);
cmd.Parameters.AddWithValue("@base", base1);

cmd.ExecuteNonQuery(); // <--- this line here

con.Close(); 

我还强烈建议您将连接包装在 using 中,以免意外将其打开:

using(SqlConnection con = new SqlConnection(...))
{
    con.Open();

    /*
        rest of code here
    */

    con.Close();
}

【讨论】:

  • 这正是我缺少的 cmd.Exec... 行!谢谢!!!
  • 没问题,很高兴能帮上忙。
  • 还有一个问题要问你。我在此页面上有多个复选框。如何设置根据问题编号更改“问题”列的更新语句?
猜你喜欢
  • 1970-01-01
  • 2014-07-14
  • 1970-01-01
  • 2013-02-18
  • 2014-01-12
  • 2015-06-27
  • 2015-09-18
  • 2015-12-22
  • 2012-07-16
相关资源
最近更新 更多