要解决这个问题很简单 只要保存控件的视图状态就可以了 我们可以用viewstate来保存 也可以用静态变量来保存 由于aspx页面周期在每次load事件里都会还原视图数据 所以后台添加的控件会被从清理掉 需要手工编码恢复 下面是一个简单示例 当然你可以使用viewstate 我用的静态变量
aspx前台代码:
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="button1" runat="server" Text="创建" onclick="Button1_Click" />
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
<asp:Button ID="id2" runat="server" Text="获取所有值" onclick="id2_Click" />
</div>
</form>
</body>
后台代码:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//还原控件
RestoreTextBox()
}
//静态变量存储控件列表
static List<TextBox>txtlist = new List<TextBox>()
//控件id
static int id = 1
protected void Button1_Click(object sender, EventArgs e)
{
var txt = new TextBox
{
ID=id.ToString(),
Text="Sample textbox " + id.ToString()
}
this.Panel1.Controls.Add(txt)
txtlist.Add(txt)
//id自增1
id++
}
/// <summary>
/// 还原控件
/// </summary>
void RestoreTextBox()
{
foreach (var item in txtlist)
{
if (item != null)
{
this.Panel1.Controls.Add(item)
}
}
}
/// <summary>
/// 读取textbox的值
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void id2_Click(object sender, EventArgs e)
{
foreach (Control item in Panel1.Controls)
{
if (item is TextBox)
{
Response.Write((item as TextBox).Text+"</br>")
}
}
}
}
'vb.net2008Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim j_MyButton As New ArrayList
For i = 0 To 5
Dim k1 As New Button
k1.SetBounds(20, 22 * i, 100, 20) '设置位置和大小(x y w h)
k1.Visible = True
AddHandler k1.Click, AddressOf my_button '委托点击事件
Me.Controls.Add(k1) '在主窗口内加入控件
j_MyButton.Add(k1)
j_MyButton(i).name = "发现" &i &"个MM"
j_MyButton(i).text = "My butten " &i
Next
End Sub
Private Sub my_button(ByVal sender As System.Object, ByVal e As System.EventArgs)
TextBox1.AppendText(sender.name &vbCrLf)
End Sub
End Class
自己在窗体上加一个按钮,以下是详细代码(整个类)Public Class Form1
Private N As Integer '用来记添加要加入textbox的个数
Private PL As Integer = 10 'textbox相对于窗体的Left
Private PT As Integer = 10 'textbox相对于窗体的Top
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.AutoScroll = True '窗体自动显示滚动条
N = 10 '初始化N为10
For i = 1 To N
Dim newtextbox As New TextBox
newtextbox.Left = PL
newtextbox.Top = PT
Me.Controls.Add(newtextbox)
PT += newtextbox.Height + 10 '各 newtextbox上下间隔10-------PL不变是希望左对齐
Next
End Sub
End Class
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)