You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# ASP.NET中用字符串作控件ID:点击按钮复制文本框内容失败怎么解决?

问题解决方法

直接使用控件ID(优先方案)

如果TextBox2没有嵌套在Panel、ContentPlaceHolder、GridView这类命名容器控件里,直接通过控件ID访问即可,无需使用Page.FindControl:

protected void Button1_Click(object sender, EventArgs e) 
{ 
    TextBox2.Text = TextBox1.Text; 
}

处理控件嵌套在命名容器的情况

如果TextBox2嵌套在某个命名容器(比如Panel、GridView行)中,Page.FindControl无法直接定位到它,需要先找到父容器,再在父容器内调用FindControl:
示例:假设TextBox2在ID为Panel1的Panel控件中

protected void Button1_Click(object sender, EventArgs e) 
{ 
    Panel parentPanel = Page.FindControl("Panel1") as Panel;
    if(parentPanel != null)
    {
        TextBox targetTxt = parentPanel.FindControl("TextBox2") as TextBox;
        if(targetTxt != null)
        {
            targetTxt.Text = TextBox1.Text;
        }
    }
}

检查ViewState设置(可选)

若页面或TextBox2的EnableViewState属性被设为false,可能导致控件状态无法正常维护,确保该属性值为true(默认即为true,除非手动修改)。


内容的提问来源于stack exchange,提问作者fateh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 03:35:14