通过循环遍历控件清除下拉列表

本文关键字:清除 下拉列表 控件 遍历 循环 | 更新日期: 2023-09-27 18:08:12

我正在尝试循环通过面板中的每个控件并清除所有内容,如果它是一个下拉列表。

我有:

private void ClearOut()
{
    foreach (Control list in MainPanel.Controls)
    {
        if (list.ToString().Equals("System.Web.UI.WebControls.DropDownList"))
        {
            //Clear it out here
        }
    }
}

这段代码确实找到了每个下拉列表,但是我不知道如何清除它们,一旦我到达那里。我不能使用下拉列表的任何属性,如selecteindex或items.clear()。

通过循环遍历控件清除下拉列表

using System.Linq;
using System.Web.UI.WebControls;
foreach (DropDownList list in MainPanel.Controls.OfType<DropDownList>())
{
    list.Items.Clear();
}

或相同的,但手动:

foreach (Control c in MainPanel.Controls)
{
    DropDownList list = c as DropDownList;
    if (list != null)
    {
        list.Items.Clear();
    }
}

使用

if(list is DropDownList)
{
DropDownList DDL = list as DropDownList;
DDL.Items.Clear();
}