往Panel里添加一个Label
有一个Panel,ID为Panel1
有一个Button,ID为Button1
我每点击Button一次,就往Panel里添加一个Label
为什么只能添加一个??最新添加的总是覆盖了前一个,是怎么回事?
protected void Button1_Click(object sender, EventArgs e)
{
string time = DateTime.Now.Second.ToString();
Label lbl = new Label();
lbl.Text = time;
lbl.ID = time;
this.Panel1.Controls.Add(lbl);
}
------解决方案--------------------对于动态增加的控件,你可以使用 ViewState 保存他们的状态,然后在每次 Page_Load 的时候重新加载,否则就会出现楼主的情况。
------解决方案--------------------请参考
private void Page_Load(object sender, System.EventArgs e)
{
if(ViewState[ "count "] != null)
{
int count = Convert.ToInt32(ViewState[ "count "]);
for(int i = 0; i < count; i++)
{
Label lbl = new Label();
lbl.Text = "aa ";
lbl.ID = "Label " + i;
this.PlaceHolder1.Controls.Add(lbl);
}
}
}
private void Button1_Click(object sender, System.EventArgs e)
{
AddControls();
}
public void AddControls()
{
Label lbl = new Label();
lbl.Text = "aa ";
lbl.ID = "Label " + Convert.ToInt32(ViewState[ "count "]);
ViewState[ "count "] = Convert.ToInt32(ViewState[ "count "]) + 1;
this.PlaceHolder1.Controls.Add(lbl);
}
如果你要打算标签上显示当前时间,还要用变量存放
------解决方案--------------------把Panel1的属性设置加一条 EnabledViewState= "true ", Panel1中原来有一个 Label
完整后台代码(已测试):
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label1.Text = idtime();
Label1.ID = idtime();
Panel_Load();
}
}
private void Panel_Load()
{
ArrayList AL = new ArrayList();
foreach (Control LB in Panel1.Controls)
{
if (LB.GetType().ToString() == "System.Web.UI.WebControls.Label ")
{
Label labl = (Label)LB;
AL.Add(labl);
}
}
Session.Add( "label ",AL);
}
private void GetInfo() //获取当前AL中Label集的信息
{
ArrayList AL = new ArrayList();
AL = (ArrayList)Session[ "label "];
if (Session[ "label "] != null)
{
for (int i = 0; i < AL.Count; i++)
{
Panel1.Controls.Add((Label)AL[i]);
}
}
}
private void AddLabel() //动态添加Label的处理
{
ArrayList Al = new ArrayList();
this.Panel1.Controls.Clear();
GetInfo();
Label LB = new Label();
LB.Text = idtime();
LB.ID = idtime();
Panel1.Controls.Add(LB);
Panel_Load();
}
public string idtime()
{
string tim;
tim = DateTim