c# - ASP.NET 从代码隐藏切换控件可见性

标签 c# asp.net code-behind

我有两个不确定是否相关的问题:

我有两个 DropDownList 控件(最初设置为不可见)和一个自动回发行为设置为 true 的 RadioButtonList 控件。

每当回发发生时,我都想从 RadioButtonList 控件中读取 SelectedValue 属性 - 并根据它,使其中一个 DropDownLists 可见。

这是我的问题:

1) 我无法通过 ID 直接引用 RadioButtonList 控件。 designer.cs 文件似乎没有生成 RadioButtonList 或 DropDownList 控件。即使我手动将控件添加到 designer.cs 文件,它们也会在重新生成时丢失。这是预期的行为吗?

2) 我尝试在 Page_Load() 方法中使用 Page.FindControl 属性。

if(Page.PostBack==true)
{
    RadioButtonList rbl = (RadioButtonList)Page.FindControl("RadioButtonList1");
    if(rbl.SelectedValue=="optionA")
    {
         DropDownList ddA = (DropDownList)Page.FindControl("DropDownListA");
         ddA.Visible = true;   
    }
    else
    {
         DropDownList ddB = (DropDownList)Page.FindControl("DropDownListB");
         ddB.Visible=true;
    }
}

但是我在 if 条件下得到了 NullReferenceException。

我完全走错路了吗?有人会指导我实现我想做的事情的最佳方法吗?

另外,我该怎么做才能让 designer.cs 文件加载控件?


编辑:/facepalm

我自己想通了。我忘记了我正在使用表格内的控件。

一旦我将控件移到表格之外,我就可以直接引用 ID。

缺乏 sleep 和咖啡是罪魁祸首。我很抱歉。感谢您的帮助!

最佳答案

Page.FindControl 不是递归的,即如果 dropdownlist1 控件在其他控件中,它将返回 null。 检查此链接以获取详细信息,看看您是否能够正确找到下拉列表。

http://www.mha.dk/post/Recursive-PageFindControl.aspx

关于c# - ASP.NET 从代码隐藏切换控件可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7937887/

相关文章:

.net - ASP.NET 2.0编译错误: Make sure that the class defined in this code file matches the 'inherits' attribute

visual-studio-2012 - 将现有的XAML文件添加到Visual Studio 2012

c# - 从中继器中的代码后面引用控件 ID

c# - 如何处理 LINQ 返回的数据类型

c# - 如何使用 C# 查找系统缓存和空闲内存

c# - 什么是 ASP.NET Core MVC 等同于 Request.RequestURI?

c# - 如何将依赖项注入(inject) asp.net core 中的模型?

c# - C# 中的字符串比较性能

c# - 数据库队列的并行处理

jquery - 使用 Jquery 获取 Kendo NumericTextBox 值