如何映射复选框以在提交后更新数据库



我需要为@email和dropdownlist中的base使用会话dataTable电子邮件值。

protected void Page_Load(object sender, EventArgs e)
    {
        DropDownList1.DataSource = (DataTable)Session["dt"];
        DropDownList1.DataValueField = "base";
        DropDownList1.DataTextField = "base";
        DropDownList1.DataBind();
    }

    string str;
    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;";
    con.Open();
    SqlCommand cmd = new SqlCommand(sql, con);

    cmd.Parameters.AddWithValue("@email", Session.dt.email);
    cmd.Parameters.AddWithValue("@str", str);
    cmd.Parameters.AddWithValue("@base", DropDownList1.base);
}

}

Session中读取值的语法错误,不能使用Session.dt.email

您需要从Session中读取DataTable,并将其转换为DataTable,如下所示:

DataTable theDataTable = null;
// Verify that dt is actually in session before trying to get it
if(Session["dt"] != null)
{
    theDataTable = Session["dt"] as DataTable;
}
string email;
// Verify that the data table is not null
if(theDataTable != null)
{
    email = dataTable.Rows[0]["Email"].ToString();
}

现在,您可以在SQL命令参数中使用email字符串值,如下所示:

cmd.Parameters.AddWithValue("@email", email);

更新:

您将希望在Page_Load中的下拉列表绑定中检查IsPostBack,因为在发布代码时,它将在每次加载页面时绑定下拉列表,而不仅仅是第一次,从而破坏用户所做的任何选择。

相反:

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        DropDownList1.DataSource = (DataTable)Session["dt"];
        DropDownList1.DataValueField = "base";
        DropDownList1.DataTextField = "base";
        DropDownList1.DataBind();
    }
}

现在,数据库参数逻辑中的base值应该是用户选择的值。

最新更新