简体   繁体   English

如何在ASP.NET的Dropdownlist上获取当前项目

[英]How to get current item on Dropdownlist for ASP.NET

My design code : 我的设计代码:

<asp:DropDownList ID ="DropDownList1" runat="server" EnableViewState="true"  AutoPostBack ="true" CssClass="ddl" DataSourceID="SqlDataSource1" DataTextField="CategoryName" DataValueField="CategoryId" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Categories]"></asp:SqlDataSource>

C# code: C#代码:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Response.Redirect("Products.aspx?catId=" + DropDownList1.SelectedValue);
    }

In database category table: 在数据库类别表中:

Book 1
Movie 2
Game 3
Music 4

Book is always current item of drop down list. 书籍始终是下拉列表的当前项目。 when i select others, their pages load but dropdownlist's current value is book and i can'response book's page. 当我选择其他人时,他们的页面会加载,但dropdownlist的当前值为book,而我无法回复该书的页面。

I think that the problem is that the list binds with the SqlDataSource on every postback so you are always getting the value of the first item. 我认为问题在于该列表在每次回发时都与SqlDataSource绑定,因此您始终会获得第一项的值。

To make sure that that's the problem, change the order of the select to DESC and see if you're always getting the last item. 为了确保这是问题所在,请将选择的顺序更改为DESC,然后查看是否总是得到最后一个项目。

change you're SQL to 改变你的SQL

SELECT * FROM [Categories] ORDER BY CategoryId DESC

And see if you're always getting 4 . 看看你是否总是得到4

If that's the problem then you need to bind the list by code always within page load like below: 如果那是问题,那么您需要始终在页面加载内通过代码绑定列表,如下所示:

if(!Page.IsPostback)
{
    // code here
}

You can try two approach Either move the dropdown populating code in the Page_Load and encapsulate the code with 您可以尝试两种方法:将下拉填充代码移动到Page_Load中,然后将代码封装为

if(!Page.IsPostBack)
{
  //your code
}

or 要么

<%
if(!Page.IsPostBack)
{ %>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Categories]"></asp:SqlDataSource>
<%}
%>

Since you are doing a redirect, this means your page is being loaded again with the default binding, making first item selected by default, subscribe to the data bound event and perform selection based on the query string parameter. 由于您正在执行重定向,因此这意味着将使用默认绑定再次加载页面,默认情况下将第一项选中,订阅数据绑定事件并根据查询字符串参数执行选择。

ASPX ASPX

<asp:DropDownList  OnDataBound="DropDownList1_DataBound" ...

C# C#

protected void DropDownList1_DataBound(object sender, EventArgs e)
{
   if(!IsPostBack){
     string selectedValue = Request.QueryString["catId"];
     if(!string.IsNullOrEmpty(selectedValue))
       DropDownList1.SelectedValue = selectedValue;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM