Items.Count为列表框返回0

时间:2013-09-11 13:22:47

标签: asp.net vb.net

我正在尝试使用下面的代码将列表中的项目存储到会话中。出于某种原因,当我调试代码时,即使列表框中有多个项目,计数也会返回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);

  }

1 个答案:

答案 0 :(得分:1)

我猜你的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