我认为您想在每个按钮单击时添加 10 个动态控件。您面临的问题是,在第一次单击时,它会添加 10 个按钮控件,而在随后的单击中,它会覆盖以前的控件。每次请求页面时都会创建动态控件,因此您必须在每次请求时创建它们。
我编写了以下代码来解决您的查询并且它有效:
// Aspx code
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
<asp:Button ID="Button2" runat="server" Text="Button" />
<asp:Label ID="l1" runat="server" Text="0"></asp:Label>
<asp:Label ID="l2" runat="server" Text="0"></asp:Label>
// Code BEhind
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim i As Integer = 0
Dim j As Integer = 0
l1.Text = l2.Text
l2.Text = Val(l2.Text) + 10
i = Val(l1.Text)
j = Val(l2.Text)
MsgBox(i & " " & j)
Dim lst As List(Of Integer) = New List(Of Integer) 'Create a list of integer type
lst.Add(i) 'Save value of i
lst.Add(j)
If Not Session("id_0") Is Nothing Then ' Will Check session for First Click exist or not
For k As Integer = 0 To DirectCast(Session("click"), Integer)
Dim mylst As List(Of Integer) = New List(Of Integer)
mylst = DirectCast(Session("id_" & k), List(Of Integer)) ' Assign Session Value to List
If Not mylst Is Nothing Then
WriteControls(mylst(0), mylst(1)) ' Call the function
End If
Next
End If
Session("id_" & DirectCast(Session("click"), Integer)) = lst ' Saves the entire list in Session
WriteControls(i, j) ' Function Call
End Sub
Private Sub WriteControls(i As Integer, j As Integer) ' Function to write button control
While (i < j)
Dim b As Button = New Button()
b.ID = "b" + i.ToString()
b.Text = b.ID
b.ViewStateMode = UI.ViewStateMode.Enabled
Panel1.Controls.Add(b)
i = i + 1
End While
Session("click") = DirectCast(Session("click"), Integer) + 1
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Session("click") = 0 ' Stores the no. of Clicks of the button
End If
End Sub
' Output
' If I press three times button then there will be 30 buttons
b0 b1 b2 b3 b4 ............................................... b29
20 30