C# 使用代码隐藏获取div

C# 使用代码隐藏获取div,c#,updatepanel,C#,Updatepanel,我有一个div,其驻留方式如下: 母版页>内容页>内容>更新面板>表格>div>gridview 我尝试使用以下方法获取div的宽度: <div runat="server" id="gridViewWrapper" style="width:820px;"> HtmlGenericControl curHeightctrl = (HtmlGenericControl)this.FindControl("gridViewWrapper"); string curWidth = Co

我有一个div,其驻留方式如下: 母版页>内容页>内容>更新面板>表格>div>gridview

我尝试使用以下方法获取div的宽度:

<div runat="server" id="gridViewWrapper" style="width:820px;">

HtmlGenericControl curHeightctrl = (HtmlGenericControl)this.FindControl("gridViewWrapper");
string curWidth = Convert.ToString(curHeightctrl.Style["width"]);
System.Diagnostics.Debug.Write(curWidth.ToString());

HtmlGenericControl curHeightctrl=(HtmlGenericControl)this.FindControl(“gridViewWrapper”);
字符串curWidth=Convert.ToString(curHeightctrl.Style[“width”]);
System.Diagnostics.Debug.Write(curWidth.ToString());

但是我不能得到宽度。我已经花了5个小时来做这个,用谷歌搜索它,直到我的手指麻木。因为div是在内容页上生成的,而不是从母版页生成的,所以它似乎应该可以工作。(我可能使用了一些不正确的语言)

您不需要
FindControl
,您可以通过其ID直接访问代码中的控件

Aspx(保持不变):

另外请注意,
Style[“width”]
已经是一个字符串(它将直接打印
820px
),因此您不需要
转换.ToString

简单使用:

string curWidth = curHeightctrl.Style["width"];

首先,请在HTML中关闭div标记(注意它的末尾/>而不仅仅是>)


gridViewWrapper无需调用FindControl即可访问,因为您在标记中添加了runat=“server”

此处的正确答案。谢谢。你说得对,部门需要关闭了。它在我的标记中,但我只处理了div的开头。我应该把它关闭,以便我的示例更完整。
string width = gridViewWrapper.Style["width"];
System.Diagnostics.Debug.Write(width);
string curWidth = curHeightctrl.Style["width"];
<div runat="server" id="gridViewWrapper" style="width:820px;"/>
<div runat="server" id="gridViewWrapper" style="width:820px;"></div>
string width = gridViewWrapper.Attributes.CssStyle["width"];