Asp.net 如何映射复选框以在提交后更新数据库。
我需要为@email和dropdownlist中的base使用会话数据表email值Asp.net 如何映射复选框以在提交后更新数据库。,asp.net,sql,sql-server,Asp.net,Sql,Sql Server,我需要为@email和dropdownlist中的base使用会话数据表email值 protected void Page_Load(object sender, EventArgs e) { DropDownList1.DataSource = (DataTable)Session["dt"]; DropDownList1.DataValueField = "base"; DropDownList1.DataTextField = "b
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.dt.email
您需要从会话
中读取数据表
,并将其转换为数据表
,如下所示:
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();
}
cmd.Parameters.AddWithValue("@email", email);
现在,您可以在SQL命令参数中使用email
字符串值,如下所示:
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();
}
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
值应该是用户选择的值。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);似乎我得到了一个错误:错误1使用未分配的局部变量'email',你放了字符串email
使用与数据库调用相同的方法?我的答案中的所有代码都应该与数据库逻辑在同一个方法中。但是,数据库没有更新。有什么建议吗?