我正在尝试获取一个字符串数组(从上一页的列表框中填充并通过Session传递)并将其显示在标签中,这就是我获取数组的方式:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles CheckOut.Click
Dim x = ListBox1.GetSelectedIndices.Count
Dim ListPNames(x) As String
Dim i As Integer
i = 0
For Each item As String In ListBox1.GetSelectedIndices
ListPNames(i) = (ListBox1.SelectedItem).ToString
i = i + 1
Next
Session("SlctdPhones") = ListPNames(x)
Response.Redirect("CheckOut.aspx")
End Sub
这就是我试图展示它的方式:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim SlctdPhones() As String = CType(Session.Item("SlctdPhones"), Array)
Dim i As Integer
Label3.Text = ""
For i = 0 To SlctdPhones.Length - 1
Label3.Text += SlctdPhones(i).ToString() + Environment.NewLine
Next
End Sub
它给了我一个错误:对象引用未设置为对象的实例。当它到达SlctdPhones.Length - 1行!! 我不知道如何修复它,也是我的数组代码正确(一切都正确存储在其中?)
答案 0 :(得分:2)
您声明For
循环如下:
For Each item In ...
但是从来没有在循环体中使用item
变量。相反,您继续使用相同的SelectedItem
属性。您想要将整个方法更改为:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles CheckOut.Click
Dim PNames As New List(Of String)()
For Each index As Integer In ListBox1.GetSelectedIndices
PNames.Add(ListBox1.Items(index).Value)
Next
Session("SlctdPhones") = PNames
Response.Redirect("CheckOut.aspx")
End Sub
修复后,Page_Load可以执行此操作:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim SlctdPhones As List(Of String) = TryCast(Session.Item("SlctdPhones"), List(Of String))
If SlctdPhones Is Nothing OrElse SlctdPhones.Length = 0 Then
'Something went wrong here!
Return
End If
Label3.Text = String.Join("<br/>", SlctdPhones.ToArray())
End Sub
但我真的很高兴看到你使用数据控件而不是将<br/>
填入标签。这是ListView的标记:
<asp:ListView ID="ListView1" runat="server">
<LayoutTemplate>
<ul>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li><%# Container.DataItem.ToString() %></li>
</ItemTemplate>
<EmptyDataTemplate>
<p>Nothing here.</p>
</EmptyDataTemplate>
</asp:ListView>
然后Page_Load更简单:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
ListView1.DataSource = Session.Item("SlctdPhones")
ListView1.DataBind()
End Sub
答案 1 :(得分:1)
在显示页面上,使用Literal而不是Label
Dim SlctdPhones() As String = CType(Session.Item("SlctdPhones"), Array)
Dim result as String = string.Join("<br>", SlctdPhones) 'Instead of <br> try Environment.NewLine as well
YourLitetal = result
希望这有帮助!