刷新页面时,dropdownlist保持选定值不变

时间:2014-03-27 15:05:05

标签: asp.net vb.net visual-studio-2012

我有一个如下所示的下拉列表:

<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后刷新页面时实现这一点,下拉列表不会返回“ - 选择一个 - ”,而是保留其最后选择的项目。我想知道它的解决方案是什么?

感谢您的建议!

2 个答案:

答案 0 :(得分: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 Code-Behind:

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

答案 1 :(得分:1)

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

查看此forum以了解实现此目标的其他方法。