1

我是 asp.net 的新手(在经典 asp 编程多年后)。我正在尝试构建一个向字符串添加内容的页面。

我的代码如下:

默认.aspx

<body>
<form id="form1" runat="server">
<div>
<p><asp:textbox id="tb" runat="server"></asp:textbox></p>
<asp:Panel ID="tbPanel" runat="server"></asp:Panel>
</div>
</form>
</body>

后面的代码:

Partial Class demo_Default
Inherits System.Web.UI.Page


Public Property gesStr As String

Set(value As String)

ViewState("gesStr") = value

End Set

Get

Dim o As Object = ViewState("gesStr")

If o Is Nothing Then

Return ""

Else

Return o

End If

End Get

End Property


Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim anzeigeStr As String = ""
If Page.IsPostBack Then
Else
gesStr = "1;"
End If
tb.Text = gesStr


Dim iButton As New Button
iButton.Text = "add"
iButton.CommandArgument = "1;"
AddHandler iButton.Click, AddressOf add
tbPanel.Controls.Add(iButton)


Me.anzeige()


End Sub


Private Sub add(ByVal sender As Object, ByVal e As EventArgs)
Dim myButton As Button = DirectCast(sender, Button)
Dim addString As String = myButton.CommandArgument
gesStr += addString
End Sub


Private Sub anzeige()
Dim gesArray As Array = Split(gesStr, ";")
For xLauf As Integer = 0 To UBound(gesArray) - 1
Dim anzLabel As New Label
anzLabel.Text = "<p>" & gesArray(xLauf) & "</p>"
tbPanel.Controls.Add(anzLabel)
Next




End Sub

End Class

问题:

按下按钮将导致 a postBack,但直到第二次按下按钮后才会出现添加的结果。期望的结果是子在第一次按下按钮后在循环内显示正确的数组。

非常感谢您的帮助!

4

1 回答 1

0

每次单击按钮时,您都需要调用函数 anzeige() 并将 gesStr 值绑定到文本框控件。请看下面的代码:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Page.IsPostBack Then
        Else
            gesStr = "1;"
        End If
        tb.Text = gesStr
        Dim iButton As New Button
        iButton.Text = "add"
        iButton.CommandArgument = "1;"
        iButton.CommandName = "1;"
        AddHandler iButton.Click, AddressOf add
        tbPanel.Controls.Add(iButton)

    End Sub

    Private Sub add(ByVal sender As Object, ByVal e As EventArgs)

        Dim myButton As Button = DirectCast(sender, Button)
        Dim addString As String = myButton.CommandArgument
        gesStr += addString

        anzeige()
    End Sub


    Private Sub anzeige()
        Dim gesArray As Array = Split(gesStr, ";")
        For xLauf As Integer = 0 To UBound(gesArray) - 1
            Dim anzLabel As New Label
            anzLabel.Text = "<p>" & gesArray(xLauf) & "</p>"
            tbPanel.Controls.Add(anzLabel)
        Next

        'Bind gesStr value to the textbox control
        tb.Text = gesStr

    End Sub
于 2012-07-17T05:33:51.560 回答