如何使用静态ClientIDMode访问动态添加到页面的控件

本文关键字:控件 添加 动态 何使用 静态 ClientIDMode 访问 | 更新日期: 2023-09-27 18:01:35

我有一个简单的页面,有1个占位符和2个按钮("添加行","获取值"),没有别的。当我点击添加行按钮时,我创建了一个动态表,并在它的单元格中放置了一些控件,设置ClientIDMoode=static:

private void CreateTableWithSession(bool FirstLoad)
{
    Table tbl;
    int Row;
    if (Session["tbl"]==null)
    {
        tbl = new Table();
    }
    else
    {
        tbl = (Table)Session["tbl"];
    }
    if (FirstLoad == true)
    {
        tbl.Rows.Clear();
    }
    //////////////////////////////////////////////////
    if (Session["Row"] == null)
    {
        Row = 0;
    }
    else
    {
        Row = int.Parse(Session["Row"].ToString());
    }
    if (FirstLoad == true)
    {
        tbl.Rows.Clear();
    }
    //////////////////////////////////////////////////
    TableRow tr1 = new TableRow();
    TableCell tc = new TableCell();
    TextBox txtBoxUserName = new TextBox();
    txtBoxUserName.ClientIDMode = System.Web.UI.ClientIDMode.Static;
    txtBoxUserName.Text = "0";
    Col++;
    txtBoxUserName.ID = "RowNo" + Row.ToString() + "ColumnNo" + Col.ToString();
    tc.Controls.Add(txtBoxUserName);
    tc.Width = 200;
    tc.VerticalAlign = VerticalAlign.Middle;
    tc.HorizontalAlign = HorizontalAlign.Center;
    tr1.Cells.Add(tc);
    tc = new TableCell();
    TextBox txtBoxPassword = new TextBox();
    txtBoxPassword.ClientIDMode = System.Web.UI.ClientIDMode.Static;
    txtBoxPassword.Text = "0";
    Col++;
    txtBoxPassword.ID = "RowNo" + Row.ToString() + "ColumnNo" + Col.ToString();
    tc.Controls.Add(txtBoxPassword);
    tc.Width = 200;
    tc.VerticalAlign = VerticalAlign.Middle;
    tc.HorizontalAlign = HorizontalAlign.Center;
    tr1.Cells.Add(tc);
    tbl.Rows.Add(tr1);
    Session["tbl"] = tbl;
    PlaceHolder1.Controls.Add(tbl);
}

和我想当用户点击"获取值"按钮,获得2个文本框值(动态添加)。但是每次返回Null

TextBox txtBoxUserName = this.FindControl("RowNo1ColumnNo1") as TextBox;

我如何修复这个和访问文本框值?

谢谢

如何使用静态ClientIDMode访问动态添加到页面的控件

在您可以访问之前应该重新创建动态创建的控件,我确信当您点击Get Value按钮时您不会创建控件。你会有办法的……

protected void AddRow_Click(object sender, EventArgs e)
{
   CreateTableWithSession()
   ...................
}
protected void GetValue_Click(object sender, EventArgs e)
{
   CreateTableWithSession()
   TextBox txtBoxUserName = this.FindControl("RowNo1ColumnNo1") as TextBox;
   ........................
}