在asp.net中使用下拉名称作为变量

本文关键字:变量 net asp | 更新日期: 2023-09-27 18:18:50

我想在asp.net网页中使用下拉列表作为变量。

我们有10个下拉列表id- ddl1,ddl2,....ddl10。我的要求是,我需要显示和隐藏代码后面的文件

    <div id ="divContainer" class="field" runat="server">
    <asp:Label ID="lblmsg1" runat="server" Text="" CssClass="fieldtxt">   
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="fieldtxtbox1" OnSelectedIndexChanged="ddlCommand_SelectedIndexChanged">
     </asp:DropDownList>
    <asp:DropDownList ID="DropDownList2" runat="server" CssClass="fieldtxtbox1" OnSelectedIndexChanged="ddlCommand_SelectedIndexChanged">
     </asp:DropDownList>
    <asp:DropDownList ID="DropDownList3" runat="server" CssClass="fieldtxtbox1" OnSelectedIndexChanged="ddlCommand_SelectedIndexChanged">
     </asp:DropDownList>
     <asp:DropDownList ID="DropDownList4" runat="server" CssClass="fieldtxtbox1" OnSelectedIndexChanged="ddlCommand_SelectedIndexChanged">
    </asp:DropDownList>
    //like this 10 different DropDownList           
    </div>

我有一个循环来做这个。我需要这样的东西……

ddl[i].Visible = true; 

当我尝试这个时,得到了类似

的错误

System.Web.UI.WebControls。"下拉列表"是一个"类型",但像"变量"一样使用

请帮

在asp.net中使用下拉名称作为变量

应该可以了

DropDownList ddls = null;
for (int i = 1; i <= 10; i++) {
    ddls = (DropDownList)this.FindControl("DropDownList" + i);
    if (ddls != null) {
        ddls.Visible = true;
    }
}

控件应该是页面的直接子控件。如果它们嵌入到其他服务器控件中,如FormView, GridView等,或者在母版页上,那么你必须将该控件或母版与FindControl

结合使用
Why not using javascript?
//save the div in a var
//check the name of the div in the generated html, it might be different from the name you have in asp.net
var divContainer = document.getElementById("divContainer");
//get all ddl contsols by Tag (tag for ddl is select)
var ddls = divContainer.GetElementByTag("select");
//iterate through the found select controls from the div and set them to visible
for (var i = 0, len = ddls.length; i < len; ++i)
{
     ddls[i].style.display='block';
}