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

ASP.NET C#如何修改集合中匹配控件对象的ReadOnly属性

解决方案

你代码的核心问题有两处:一是类型匹配逻辑写反,二是没有对找到的控件做安全类型转换就尝试访问控件特有的属性。另外注意DropDownList没有原生的ReadOnly属性,如需只读效果通常用Enabled属性控制,或者用前端JS实现不灰化的只读效果。

修改后的可用代码如下:

foreach (Control ctlMaster in Page.Controls)
{
    if (ctlMaster is MasterPage)
    {
        foreach (Control ctlForm in ctlMaster.Controls)
        {
            if (ctlForm is HtmlForm)
            {
                foreach (Control ctlContent in ctlForm.Controls)
                {
                    if (ctlContent is ContentPlaceHolder)
                    {
                        foreach (Control ctlChild in ctlContent.Controls)
                        {
                            if (ctlChild is Panel)
                            {
                                foreach (Control ctlform in ctlChild.Controls)
                                {
                                    if (!string.IsNullOrEmpty(ctlform.ID))
                                    {
                                        Debug.WriteLine("ID = [" + ctlform.ID + "]");
                                        Debug.WriteLine("UniqueID = [" + ctlform.UniqueID + "]");
                                        Debug.WriteLine("type = [" + ctlform.GetType() + "]");
                                        
                                        // 匹配TextBox并切换只读状态
                                        TextBox targetTxt = ctlform as TextBox;
                                        if (targetTxt != null)
                                        {
                                            targetTxt.ReadOnly = !targetTxt.ReadOnly;
                                            continue;
                                        }
                                        
                                        // 匹配DropDownList并切换禁用状态
                                        DropDownList targetDdl = ctlform as DropDownList;
                                        if (targetDdl != null)
                                        {
                                            // 如需只读不灰化可替换为自定义JS逻辑,此处为常规禁用方案
                                            targetDdl.Enabled = !targetDdl.Enabled;
                                            continue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

额外优化建议:可以把多层嵌套的控件遍历逻辑封装为递归方法,不需要硬编码MasterPage、ContentPlaceHolder、Panel的层级,适配性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:54:06