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

如何将ASP.NET TextBox控件从.ascx.cs提取到其他类并动态修改Enabled属性

问题解决代码

第一步:统一绑定事件

所有DropdownList的OnSelectedIndexChanged都绑定到同一个公共处理方法,示例如下:

<asp:DropDownList ID="panelddlListedEntity" runat="server" Width="510" CssClass="formInput" 
    OnSelectedIndexChanged="CommonDDL_SelectedIndexChanged" AutoPostBack="True">
</asp:DropDownList>
<!-- 其他所有DropdownList都按上面的方式绑定同一个OnSelectedIndexChanged事件 -->

第二步:编写公共处理方法

替换原有事件方法,代码如下:

protected void CommonDDL_SelectedIndexChanged(object sender, EventArgs e)
{
    // 拿到当前触发事件的DropdownList实例
    DropDownList currentDDL = (DropDownList)sender;
    // 按命名规则拼接对应TextBox的ID
    string targetTBID = currentDDL.ID.Replace("ddl", "tb");
    // 在当前用户控件中查找对应的TextBox实例
    TextBox targetTB = (TextBox)FindControlRecursive(this, targetTBID);
    
    if (currentDDL.SelectedValue.Contains("Other"))
    {
        targetTB.Enabled = true;
    }
    else
    {
        targetTB.Enabled = false;
        // 可选:非Other选项时清空文本框内容
        targetTB.Text = string.Empty;
    }
}

// 辅助方法:递归查找控件,解决层级嵌套时FindControl找不到的问题
private Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id) return root;
    foreach (Control c in root.Controls)
    {
        Control found = FindControlRecursive(c, id);
        if (found != null) return found;
    }
    return null;
}

原代码错误说明

  • 你之前注释了sender转DropdownList的代码,自然拿不到触发事件的控件ID
  • 错误使用LoadControl加载了新的用户控件实例,该实例和当前页面正在运行的用户控件不是同一个对象,修改它的属性自然不会生效
  • 不需要手动new TextBox,直接查找页面上已存在的对应文本框控件即可

注意事项

所有DropdownList和对应的TextBox需要遵循统一的ID命名规则:下拉ID包含ddl、对应文本框ID对应位置为tb,保证Replace("ddl","tb")后能匹配到正确的文本框ID。

内容的提问来源于stack exchange,提问作者wshuo.h

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:36:06