我有一个页码下拉列表,可以从数据库查询中获取正确的值。这个列表一切正常,但我似乎无法弄清楚如何在下拉列表中保留选定的值。页码通过查询字符串传递,我将其保留为ViewState变量。我可以通过返回.aspx确认正确保留此变量。如何将该值设置为所选,但是当加载新页面时,下拉列表并不总是恢复为“1”?
我的代码背后:
public string proc;
public string page
{
get { return ViewState["page"] as string; }
set { ViewState["page"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
page = Request.QueryString["page"];
Page_Numbers();
}
public void Page_Numbers()
{
if (proc != null)
{
int totalRows;
int totalPages;
string sqlConn = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
SqlConnection sqlConnection1 = new SqlConnection(sqlConn);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = (proc);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
totalRows = Convert.ToInt32(cmd.ExecuteScalar());
totalPages = ((totalRows / 1000) + 1);
sqlConnection1.Close();
for (int i = 1; i <= totalPages; i++)
{
PageDdl.Items.Add(new ListItem(i.ToString()));
if (i == Convert.ToInt32(page))
{
PageDdl.SelectedItem.Value = page;
}
}
}
}
protected void PageDdl_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("report.aspx?proc=" + proc + "&page=" + PageDdl.SelectedItem.Text);
}
我的aspx:
<div class="totalPages">
<asp:DropDownList ID="PageDdl" runat="server"
onselectedindexchanged="PageDdl_SelectedIndexChanged"
AutoPostBack="True" Visible="True">
</asp:DropDownList>
</div>
Page: <%=page %>
在我的aspx上,显示 page 变量,以便我确认它已正确分配。
答案 0 :(得分:0)
每次加载页面时都会清除ViewState。要即使重新加载页面也要保留它,请将其存储在Session中。此外,您的Page_Load每次都会覆盖它。所以是的,你将它存储在ViewState中,但也许你想检查它是否在ViewState中而不是覆盖它?
答案 1 :(得分:0)
您可以在for循环中将所选值设置为1行:
for (int i = 1; i <= totalPages; i++)
{
PageDdl.Items.Add(new ListItem() { Text = i.ToString(), Selected = i == Convert.ToInt32(page) });
}