c# - 在 div id 上使用 FindControl 时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11416959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c# - error using FindControl on div id
提问by JasonH
I have an ASP.NET site that I am trying to access div elements by their ID from the C# code behind file. Essentially I want to see if a div element exists, and if so, alter its properties.
我有一个 ASP.NET 站点,我试图从 C# 代码隐藏文件中通过它们的 ID 访问 div 元素。本质上,我想查看 div 元素是否存在,如果存在,则更改其属性。
I've found many resources out there that point to a dozen different solutions and none of them seem to work.
我发现很多资源都指向了十几种不同的解决方案,但似乎没有一个有效。
HTML on ASP.Net Page:
ASP.Net 页面上的 HTML:
<div class="contentArea">
<div class="block" id="button1" runat="server">
Some Content Here
</div>
<div class="block" id="button2" runat="server">
Some Content Here
</div>
<div class="block" id="button3" runat="server">
Some Content Here
</div>
</div>
C# Code Behind (examples I've tried):
C# 代码隐藏(我试过的例子):
System.Web.UI.HtmlControls.HtmlGenericControl div1 = (System.Web.UI.HtmlControls.HtmlGenericControl)this.FindControl("button1");
div1.Attributes["class"] = "classNameHere";
or
或者
Control div1 = this.FindControl("button1");
div1.GetType();
When the code gets to the second line of each of the above examples, I get an error:
当代码到达上述每个示例的第二行时,我收到一个错误:
Object reference not set to an instance of an object.
你调用的对象是空的。
If I try the following:
如果我尝试以下操作:
if (div1 != null)
{
// Do Something;
}
Nothing ever happens because div1 is always set to null. Ironically, if I look at the Locals window and examine this, I can see the button# ids in the listing, so I know they are there, but the system is acting like it isn't finding the control.
什么也没有发生,因为 div1 始终设置为 null。具有讽刺意味的是,如果我查看 Locals 窗口并检查它,我可以在列表中看到 button# ids,所以我知道它们在那里,但系统表现得好像它没有找到控件一样。
My ultimate goal is to find the max id # of the button divs (looking at my html example, the max id would be 3 (button3). Maybe there is a better way to go about it, but either way, once I have my max id, I want to be able to touch each div and alter some css properties.
我的最终目标是找到按钮 div 的最大 id #(查看我的 html 示例,最大 id 将是 3(button3)。也许有更好的方法来解决它,但无论哪种方式,一旦我有了我的max id,我希望能够触摸每个 div 并更改一些 css 属性。
Although I could easily do all of this via jQuery, in this instance I need to do this in C#.
虽然我可以通过 jQuery 轻松完成所有这些,但在这种情况下,我需要在 C# 中完成。
Any help is much appreciated. If you need more info, let me know.
任何帮助深表感谢。如果您需要更多信息,请告诉我。
UPDATEI created a new C# web project from scratch. After adding a masterpage (and not altering it) and adding a webform using masterpage, I only added one line to the webform under Content ID="Content2":
更新我从头开始创建了一个新的 C# web 项目。添加母版页(而不是更改它)并使用母版页添加网络表单后,我只在 Content ID="Content2" 下的网络表单中添加了一行:
<div id="button1"></div>
From c# code behind I still run into the same exact issue as before.
从后面的 c# 代码中,我仍然遇到与以前完全相同的问题。
FINAL UPDATE AND ANSWERI'm shocked no one (including myself) caught my mistake from the above update. I never put runat="server" when I created a new project from scratch under the div. Here is how I fixed my problem under my new project from scratch:
最终更新和回答我很震惊没有人(包括我自己)从上述更新中发现我的错误。当我从头开始在 div 下创建一个新项目时,我从不放置 runat="server"。以下是我从头开始在新项目下解决问题的方法:
Add runat="server" to div:
将 runat="server" 添加到 div:
<div id="button1" runat="server"></div>
Then I did a FindControl on the ContentPlaceHolder under the MasterPage:
然后我在 MasterPage 下的 ContentPlaceHolder 上做了一个 FindControl:
ContentPlaceHolder myPlaceHolder = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
Note: This is what the ContentPlaceHolder code looks like on the Site.Master page created by default:
注意:这是默认创建的 Site.Master 页面上的 ContentPlaceHolder 代码的样子:
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
After finding this ContentPlaceHolder in code behind, I then searched within this placeholder for button1:
在后面的代码中找到这个 ContentPlaceHolder 后,我在这个占位符中搜索 button1:
using System.Web.UI.HtmlControls;
HtmlControl myControl = (HtmlControl)myPlaceHolder.FindControl("button1");
Finally I check to see if myControl is null:
最后我检查一下 myControl 是否为空:
if (myControl != null)
{
\ Do Something
}
When I ran this code, it found the div I was looking for. Here is the complete code behind all put together:
当我运行这段代码时,它找到了我正在寻找的 div。这是所有放在一起的完整代码:
using System.Web.UI.HtmlControls;
ContentPlaceHolder myPlaceHolder = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
HtmlControl myControl = (HtmlControl)myPlaceHolder.FindControl("button1");
if (myControl != null)
{
// Do Something
}
采纳答案by Kristof Claes
If your page is using a MasterPage, the div control will not be in the main collection of controls. That collection only contains the Content controls pointing to the ContentPlaceholder of your MasterPage.
如果您的页面使用 MasterPage,则 div 控件将不在主控件集合中。该集合仅包含指向 MasterPage 的 ContentPlaceholder 的内容控件。
There are three options:
共有三个选项:
- Use
FindControlon the Content control:contentControl.FindControl("button1"); - Do a recursive
FindControluntil you find the control you need - Normally, a declaration of your div control is added to your designer.cs codebehind, so you can directly access the control by its name:
button1.Attributes["class"] = "classNameHere";
- 使用
FindControl在内容控制:contentControl.FindControl("button1"); - 进行递归,
FindControl直到找到所需的控件 - 通常,您的 div 控件的声明会添加到您的 Designer.cs 代码隐藏中,因此您可以通过其名称直接访问该控件:
button1.Attributes["class"] = "classNameHere";
Update
更新
I have created a MasterPage, added a Content Page to it, and added <div id="button1" runat="server">Some text</div>to the Content Page.
我创建了一个 MasterPage,向其中添加了一个内容页面,并添加<div id="button1" runat="server">Some text</div>到了内容页面。
In the codebehind of my Content Page, I added this code:
在我的内容页面的代码隐藏中,我添加了以下代码:
protected void Page_Load(object sender, EventArgs e)
{
var control = FindHtmlControlByIdInControl(this, "button1");
if (control != null)
{
control.Attributes["class"] = "someCssClass";
}
}
private HtmlControl FindHtmlControlByIdInControl(Control control, string id)
{
foreach (Control childControl in control.Controls)
{
if (childControl.ID != null && childControl.ID.Equals(id, StringComparison.OrdinalIgnoreCase) && childControl is HtmlControl)
{
return (HtmlControl)childControl;
}
if (childControl.HasControls())
{
HtmlControl result = FindHtmlControlByIdInControl(childControl, id);
if (result != null) return result;
}
}
return null;
}
This works for me.
这对我有用。
回答by Ashwin Chandran
You need to add a runat=server attribute to any control that you want to access in code behind. See this article for more help.
您需要将 runat=server 属性添加到要在代码隐藏中访问的任何控件。请参阅此文章以获取更多帮助。
回答by Tianzhen Lin
I cannot seem to be able to reproduce your problem, any chance your DIV's are within a template control such as UpdatePanel, Repeater, or Grid?
我似乎无法重现您的问题,您的 DIV 是否位于模板控件中,例如 UpdatePanel、Repeater 或 Grid?
回答by monsieurgutix
If you add runat=serverplease add it at last of the div:
如果添加, runat=server请将其添加到 div 的最后:
This will work
这将工作
<div id="divBtn" class="mybuttonCass" runat="server">
However, this will not
然而,这不会
<div runat="server" id="divBtn" class="mybuttonCass">
By doing that, you can modify any property from codebehind as:
通过这样做,您可以将代码隐藏中的任何属性修改为:
divBtn.Style["display"] = "none";
This works even with masterpages. The div is not included in a masterpage.
这甚至适用于母版。div 不包含在母版页中。

