提交按钮和复选框不更新sql server数据库

时间:2013-08-23 18:14:36

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

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();  

    }

}

}

1 个答案:

答案 0 :(得分:0)

你错过了实际命令的执行调用:

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();
}