我的设计如下:
<asp:Label ID="lbl1" runat="server" AssociatedControlID="ddl1">
</asp:Label>
<asp:DropDownList ID="ddl1" runat="server"></asp:DropDownList>
像这样我有几个标签,我想找出与表单上每个标签关联的控件类型。是否可以获得控件类型?
您可以使用FindControl并传入AssociatedControlID
:
Control c = FindControl(lbl1.AssociatedControlID);
if(c == null) // Not found
else
{
Type t = c.GetType(); // Gets the type of the control
if(c is TextBox) // I'm a textbox
else if(c is DropDownList) // I'm a DropdownList
}
在后面的代码中试试这个:
foreach (Label lbl in this.Page.Form.Controls.OfType<Label>())
{
}