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

时间:2015-10-22 08:25:48

标签: c# asp.net loops variables drop-down-menu

我想在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.DropDownList'是'type',但用作'变量'

请帮忙

2 个答案:

答案 0 :(得分:1)

这应该可以解决问题

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一起使用

答案 1 :(得分:0)

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';
}