0

假设我有 100 个带有“状态”类的下拉列表。如何将所有具有“状态”类的 Web 控件绑定到同一个数据源,而不是一一进行?

提前致谢!

4

3 回答 3

2

所有控件都位于Page.Controls中,您可以相应地对其进行迭代:

private void Page_Load(object sender, System.EventArgs e)
{
    LoopDropDownLists(Page.Controls);
}

private void LoopDropDownLists(ControlCollection controlCollection)
{
    foreach(Control control in controlCollection)
    {
        if(control is DropDownList)
        {
            ((DropDownList)control).DataSource = //Set datasource here!
        }

        if(control.Controls != null)
        {
            LoopDropDownLists(control.Controls);
        }
    }
}

然而,我对您对 100 个 DropDownLists 的需求很感兴趣,这对用户友好吗?

于 2012-12-09T23:43:04.977 回答
1

在页面加载时,您可以循环访问表单上的控件,并在必要时根据类属性将下拉列表上的数据源属性动态设置为所需的源。

于 2012-12-09T23:39:12.993 回答
1

添加到 m.edmondsons 答案:

    /// <summary>
    /// Bind DropDown Lists with a cetain CSS Class
    /// </summary>
    /// <param name="control">Parent Control Containing Dropdown Lists</param>
    /// <param name="cssClass">Class that determines binding</param>
    /// <param name="tableToBind">Data Source</param>
    public void FindAndBindControlsRecursive(Control control, string cssClass, DataTable tableToBind)
    {   
        foreach (Control childControl in control.Controls)
        {
            if (childControl.GetType() == typeof(DropDownList))
            {
                DropDownList dd = (DropDownList)childControl;
                //Check CSS class                    
                if (dd.CssClass.IndexOf(cssClass) > -1)
                {
                    dd.DataSource = tableToBind;
                    //Set DataFields & TextFields
                    dd.DataBind();
                }
            }
            else
            {
                FindAndBindControlsRecursive(childControl, cssClass, tableToBind);
            }
        }
    }
于 2012-12-10T00:23:28.810 回答