2014-03-27 104 views
0

我有一个下拉列表如下图所示:下拉列表刷新页面时保持选定值不变

<asp:DropDownList ID="DropDownList1" cssclass="ddStyle" runat="server" DataSourceID="SqlDataSource2" DataTextField="company" DataValueField="SECid" Width="100%" AppendDataBoundItems="true" AutoPostBack="True" EnableViewState="true" ViewStateMode="Enabled"> 
    <asp:ListItem Text="--Select One--" Value="" /> 
</asp:DropDownList> 
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="DropDownList1"></asp:RequiredFieldValidator> 
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="select distinct secid, company from .... order by company"></asp:SqlDataSource> 

VB的背后是

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click 

    Dim Selection As String = Nothing 


    If Not DropDownList.SelectedValue Is Nothing Then Selection = DropDownList.SelectedValue 
    Session("Selected") = Selection 



End Sub 

我要实现的是,当我刷新页面后,我对dropdwonlist做出选择时,下拉列表将不会返回到“ - select one--”,而是保留其最后选定的项目。我想知道它有什么解决方案?

感谢您的咨询!

+0

你能告诉我你的代码 - 背后?你在Page_Load中有什么? –

+0

嗨,后面的VB代码是一个按钮点击(如上所述)。我目前没有任何page_load子。 – user3344443

+0

等一下,也许我想不明白:你不想让DropDownList在任何refreash后改变选定的项目?所以当页面刷新时,你希望DropDownList保留其最后选择的项目? –

回答

3

这里是LakshmiNarayana换货的例子:

ASPX:

<asp:DropDownList ID="DropDownList1" runat="server"> 
    <asp:ListItem Text="-- Select One --"></asp:ListItem> 
    <asp:ListItem Text="Apple"></asp:ListItem> 
    <asp:ListItem Text="Orange"></asp:ListItem> 
</asp:DropDownList> 

<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" /> 

VB代码隐藏:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
    If Not IsPostBack Then 
     If Not Session("Selected") Is Nothing Then 
      DropDownList1.SelectedValue = Session("Selected").ToString 
     End If 
    End If 
End Sub 

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click 
    Dim Selection As String = Nothing 

    If Not DropDownList1.SelectedValue Is Nothing Then 
     Selection = DropDownList1.SelectedValue 
     Session("Selected") = Selection 
    End If  
End Sub 
+0

感谢您的明确解释!我现在明白了! – user3344443

+0

非常欢迎您! –

+0

我最近意识到,当我做层叠下拉列表(不使用AJAX)时,VB代码会在刷新页面时返回错误(因为下拉列表总是返回到第一项)。我想知道是否有办法解决这个问题? – user3344443

1

一种方法可能是检查Session("Selected")值是否包含值,并将其绑定到page_load中的列表框中的!isPostback块中。

检出此forum为实现此目的的其他方法。

+0

嗨,是它像保护小组Page_reload(BYVAL发件人为对象,BYVALË作为System.EventArgs)把手Me.Load 如果DropDownList.SelectedValue =“”然后 DropDownList.DataBind() 结束如果结束 小组我试图但仍然不起作用? – user3344443

+0

感谢您的咨询!我知道了! – user3344443

+0

很高兴帮助!你非常欢迎:) – LakshmiNarayanan

相关问题