【问题标题】:Capturing the value of dynamically created TextBox and DropDownList in ASP.NET在 ASP.NET 中捕获动态创建的 TextBox 和 DropDownList 的值
【发布时间】:2016-08-30 22:49:41
【问题描述】:

我遇到了一个问题,尝试了谷歌搜索但找不到任何解决方案。

我在Page_Load 中动态创建了控件,并且我有一个静态按钮。

单击按钮时,我需要在这些控件中捕获用户输入。

现在,当我尝试使用其唯一 ID 访问控件时,将返回错误,因为该控件在运行时不可用。 :(

For 循环 - 开始

    if (dr["Type"].ToString().Trim() == "DropDown")
    {
        DropDownList ddl = new DropDownList();
        ddl.Id = "ddl" + Convert.ToString(Counter);
        ddl.DataTextField = "Text";
        ddl.DataValueField = "Value";
        ddl.DataSource = ds1;
        ddl.DataBind();
        ddl.EnableViewState = true;
        cell.Controls.Add(ddl);
    }
    else if (dr["QuestionType"].ToString().Trim() == "TextBox")
    {
        TextBox txt = new TextBox();
        txt.ID = "txt" + Convert.ToString(Counter);
        txt.EnableViewState = true;
        cell.Controls.Add(txt);
    }
    row.Cells.Add(cell);
    table.Rows.Add(row);

即使我在Btn_click 函数中执行FindControl,它表示面板有0 个控件。

var textbox = (TextBox)pnlMidTermFeedback.FindControl("txt5");

文本框始终为 NULL,尽管我有一个控件 txt5。当我执行 F12 时,我可以看到它。

请帮忙。

【问题讨论】:

  • 我通过将控件详细信息隐式添加到 Viewstate 来解决它。

标签: asp.net asp.net-3.5


【解决方案1】:

必须在每次回发时重新创建动态创建的控件:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        // Set values and properties of controls specified in markup
        ...
    }

    // Create new controls and add them to the panel
    ...
}

然后它们将在按钮事件处理程序中可用,并包含用户输入的数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    相关资源
    最近更新 更多