我想将下拉列表的选定项目保存为会话,但我总是从位置表中获得第一个结果。
ASP.net:<div>
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
</div>
c#(只是获取下拉列表的位置工作良好)
using(SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("select location_id, location_name from locations", con);
con.Open();
DropDownList1.DataTextField = "location_name";
DropDownList1.DataValueField = "location_id";
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataBind();
}
问题:总是从数据库中检索第一个位置。
protected void btnGo_Click(object sender, EventArgs e)
{
string location;
Session["userLocation"] = DropDownList1.SelectedItem;
location = Session["userLocation"].ToString();
}
只有当Page.IsPostBack
等于False
时才应该进行绑定。
原因可能是每次请求页面时都调用填充DropDownList1
的数据操作。也有可能这个数据检索发生在btnGo_Click
执行之前,因此SelectedIndex
将重置为0,这是您的情况中的第一个位置。