简体   繁体   English

在代码隐藏中找不到HTML控件

[英]Can't find HTML control in codebehind

I have a div (id=main), it contains 15 html select controls inside and their IDs are ddl1, ddl2, ddl3, ... and so on. 我有一个div(id = main),它里面包含15个html select控件,它们的ID为ddl1,ddl2,ddl3等。

Now I want to dynamically select or assign their indexes from an XML file, so I wrote this code. 现在,我想从XML文件中动态选择或分配它们的索引,因此我编写了这段代码。

private void readxml(string spath) {
  XmlDocument doc = new XmlDocument();
  doc.Load(spath);
  //doc.LoadXml(spath);
  XmlNodeList xmlnodes = doc.SelectNodes("/Hedge/*");
  for (int i=1; i <= 15; i++) {
    (main.FindControl("ddl" + i) as DropDownList).SelectedIndex = Int32.Parse(xmlnodes[i].InnerText);
  }
}

But an error is occuring here... 但是这里发生了错误...

Object reference not set to an instance of an object. 你调用的对象是空的。

It's maybe because it's not able to find the controls (HTML select controls)... Can anyone tell me the reason or solve my problem? 可能是因为找不到控件(HTML选择控件)。有人可以告诉我原因或解决我的问题吗?

您是否将runat="server"添加到控件和Id="ddl1"

In case of such markup: 在这种标记的情况下:

<div id="main" runat="server">
    <select id="ddl1" runat="server"></select>
</div>

The type of ddl1 won't be DropDownList but rather HtmlSelect, so change your code to: ddl1的类型不是DropDownList,而是HtmlSelect,因此将代码更改为:

(main.FindControl("ddl" + i) as HtmlSelect).SelectedIndex = Int32.Parse(xmlnodes[i].InnerText);

If still null error, good chance that xmlnodes is null meaning something went wrong loading the XML document or selecting the nodes. 如果仍然为null错误,则xmlnodes为null的可能性xmlnodes ,这意味着在加载XML文档或选择节点时出错。

There are two thing that may have went wrong. 有两件事可能出错了。 One is obvious 一个很明显

  (main.FindControl("ddl" + i) as DropDownList).SelectedIndex = 
            Int32.Parse(xmlnodes[i].InnerText);

Since you are not using asp.net dropdown list so you can not cast it into this. 由于您没有使用asp.net下拉列表,因此无法将其强制转换为此。 So it should be 所以应该

     (main.FindControl("ddl" + i) as HtmlSelect).SelectedIndex = 
                                                    Int32.Parse(xmlnodes[i].InnerText);

Another could be the attribute runat="server" which needs to be there if you are suing html controls and want to access it on C# page. 另一个可能是属性runat="server" ,如果您使用html controls并想在C#页面上访问它,则必须在该属性中。

   <select id="Select1" runat="server">
     <option value="1" Selected="True"> Item 1 </option>
     .....
  </select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM