如何使用关联控件 ID 获取控件的类型

本文关键字:控件 类型 获取 ID 关联 何使用 | 更新日期: 2023-09-27 18:33:29

我的设计如下:

<asp:Label ID="lbl1" runat="server" AssociatedControlID="ddl1">
</asp:Label>
<asp:DropDownList ID="ddl1" runat="server"></asp:DropDownList>

像这样,我有几个标签,我想找出与表单上每个标签关联的控件类型。是否可以获取控件类型?

如何使用关联控件 ID 获取控件的类型

在代码隐藏中尝试:

foreach (Label lbl in this.Page.Form.Controls.OfType<Label>()) 
{
}

您可以使用 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
}