我有一组相当复杂的HTML,我想要搜索这些HTML以查找符合各种条件的输入。我希望使用一些类似的东西:
private void setup()
{
masterContainer.InnerHtml = @"
<div>crazy
<div>unknown
<div>html layout
<select id='crazySelectIdentifier_id1' runat='server'>
<option value='1'>Item1</option>
<option value='2'>Item2</option>
</select>
</div>
</div>
</div>
<div>
<div>
<select id='crazySelectIdentifier_id2' runat='server'>
<option value='1'>Item1</option>
<option value='2'>Item2</option>
</select>
</div>
</div>
<div>
</div>";
}
private void recursiveTrawl(HtmlGenericControl currentOuterControl)
{
for (int i = 0; i < currentOuterControl.Controls.Count; i++)
{
HtmlGenericControl currentControl = (HtmlGenericControl) currentOuterControl.Controls[i];
if(currentControl.HasControls())
{
recursiveTrawl(currentControl);
}
else
{
String[] controlArr = currentControl.ID.ToString().Split('_');
String currentId = controlArr[1];
if (currentId.Equals("somethingspecific"))
{
//THE PROBLEM IS HERE
DropDownList dropdown = (DropDownList)currentControl;但是,我收到错误-无法将类型'System.Web.UI.HtmlControls.HtmlGenericControl‘转换为'System.Web.UI.WebControls.DropDownList’
我也尝试过使用HtmlSelect,但也出现了类似的错误。我只需要知道如何访问我感兴趣的下拉列表中的选定值。
提前谢谢。
发布于 2009-12-23 14:37:31
试试这个:
WebForm
<asp:PlaceHolder ID="PlaceHolder1" runat="server" />扩展方法
public static class ControlExtensions
{
public static void FindControlByType<TControl>(this Control container, ref List<TControl> controls) where TControl : Control
{
if (container == null)
throw new ArgumentNullException("container");
if (controls == null)
throw new ArgumentNullException("controls");
foreach (Control ctl in container.Controls)
{
if (ctl is TControl)
controls.Add((TControl)ctl);
ctl.FindControlByType<TControl>(ref controls);
}
}
}代码
string html = @"<div>
<select id='Sel1' runat='server'>
<option value='1'>Item1</option>
<option value='2'>Item2</option>
<option value='3'>Item3</option>
</select>
</div>
<div>
<select id='Sel2' runat='server'>
<option value='4'>Item4</option>
<option value='5'>Item5</option>
<option value='6'>Item6</option>
</select>
</div>";
Control ctl = TemplateControl.ParseControl(html);
PlaceHolder1.Controls.Add(ctl);
List<HtmlSelect> controls = new List<HtmlSelect>();
PlaceHolder1.FindControlByType<HtmlSelect>(ref controls);
foreach (HtmlSelect select in controls)
{
}发布于 2009-12-29 00:43:37
这种类型转换在编译时总是会出错,因为HtmlGenericControl和HtmlSelect之间没有继承关系。一个对象不能同时是这两个。一旦一个对象成功地转换为HtmlGenericControl (就像函数参数一样),编译器肯定知道它不能也是一个HtmlSelect,所以它甚至不会让您尝试转换。
即使编译起作用了,你也会在运行时得到一个错误,因为不是HtmlGenericControl。
您的解决方案是不必费心将任何内容转换为HtmlGenericControl。只需使用Control类,因为它来自Controls集合。当你知道你看到的是正确的对象时,你唯一应该做的类型转换就是HtmlSelect。
发布于 2014-01-17 22:47:47
如果您将id=“标题”赋予页面上的任何控件并在代码隐藏中执行操作,也会发生这种情况
示例:
.aspx:
<asp:Label ID="TitleName" runat="server" Text="this will change"></asp:Label> .cs:
Title.Text = Session["ClientName"].ToString();https://stackoverflow.com/questions/1950815
复制相似问题