1

我正在尝试使用下面的代码将列表中的项目存储到会话中。出于某种原因,当我调试代码时,即使列表框中有多个项目,计数也会返回 0?有什么想法我在这里做错了吗?

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    NameTextBox_AutoCompleteExtender.OnClientItemSelected = "getSelected"
End Sub

 Protected Sub cmdNext_Click(sender As Object, e As System.Web.UI.ImageClickEventArgs) Handles cmdNext.Click
    Dim n As Integer = NPListbox.Items.Count
    Dim arr As String() = New String(n - 1) {}
    For i As Integer = 0 To arr.Length - 1
        arr(i) = NPListbox.Items(i).ToString()
    Next
    Session("arr") = arr

    Response.Redirect("~/frmDescription.aspx")
End Sub 


 <script language="javascript" type="text/javascript">
       function getSelected(source, eventArgs) {
      var s = $get("<%=NameTextBox.ClientID %>").value;

      var opt = document.createElement("option");
      opt.text = s.substring(s.length - 10);
      opt.value = s.substring(s.length - 10);

      document.getElementById('<%= NPListbox.ClientID %>').options.add(opt);

  }

4

1 回答 1

2

我猜你没有任何逻辑Page_Load来填充列表框,这取决于你完成自动完成扩展器逻辑时的内容。因为,你没有,那么当Page_Load你的值消失后点击事件触发时。

将在选择自动完成扩展器时执行的逻辑放在一个方法中,然后Page_Load调用它,如下所示:

Protected Sub Page_Load(sender As Object, e As EventArgs)
    ' Put call here to populate the listbox results from autocomplete extender selection
    PopulateListBox()
End Sub

Private Sub PopulateListBox()
    ' Go to whatever resource you are using to get the values for the list box
End Sub

更新:

由于您依赖于使用客户端函数从自动完成扩展器中获取值并以这种方式填充列表框,因此您需要在Page_Load服务器端模仿该逻辑,因为如果您尝试这样做将为时已晚使用客户端,因为您需要服务器端的数据,并且所有服务器端事件都发生在服务器回发中的客户端逻辑之前。

你需要做这样的事情:

Protected Sub Page_Load(sender As Object, e As EventArgs)
    ' Only do this when page has posted back to the server, not the first load of the page
    If IsPostBack Then
        ' Put call here to populate the listbox results from autocomplete extender selection
        PopulateListBox()
    End If
End Sub

Private Sub PopulateListBox()
    ' Get value from text box
    Dim textBoxValue As String = Me.NameTextBox.Text

    ' Create new item to add to list box
    Dim newItem As New ListItem(textBoxValue)

    ' Add item to list box and set selected index
    NPListbox.Items.Add(newItem)
    NPListbox.SelectedIndex = NPListbox.Items.Count - 1
End Sub
于 2013-09-11T13:37:18.023 回答