向Web窗体添加动态控件

时间:2015-05-15 13:41:39

标签: c# asp.net viewstate

我试图在按钮点击上添加新的动态控件,但这不是添加多个标签,我也希望在回发后保留控件的状态,就像添加输入值的文本框一样。

public partial class _Default : System.Web.UI.Page
{
  List<string> ControlIDs = new List<String>();
  static int count = 0;
  protected override void LoadViewState(object savedState)
  {
    base.LoadViewState(savedState);
    ControlIDs = (List)ViewState["ControlsID"];
    foreach (string ID in ControlIDs)
    {
      count++;
      Label Dynamic_TypeinError = new Label();
      Dynamic_TypeinError.ID = ID;
      TableRow tbl_Rows = new TableRow();
      TableCell tbl_Cell = new TableCell();
      tbl_Cell.Controls.Add(Dynamic_TypeinError);
      tbl_Rows.Cells.Add(tbl_Cell);
      plc.Controls.Add(tbl_Rows);
    }
  }

  protected void Bt_AddDynamicControls_Click(object sender, EventArgs e)
  {
    count++;
    Label Dynamic_TypeinError = new Label();
    Dynamic_TypeinError.ID = "Dynamic_TypeinError" + count;
    Dynamic_TypeinError.Text = "Type in Error";
    TableRow tbl_Rows = new TableRow();
    TableCell tbl_Cell = new TableCell();
    tbl_Cell.Controls.Add(Dynamic_TypeinError);
    tbl_Rows.Cells.Add(tbl_Cell);
    plc.Controls.Add(tbl_Rows);
    ControlIDs.Add(Dynamic_TypeinError.ID);
    ViewState["ControlsID"] = ControlIDs;
  }

0 个答案:

没有答案