假设我有100个带有“状态”类的下拉列表。如何将所有带有“状态”类的webcontrol绑定到同一数据源而不是逐个进行?
提前致谢!
答案 0 :(得分: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感兴趣,这个用户友好吗?
答案 1 :(得分:1)
在页面加载时,您可以循环遍历表单上的控件,并根据类属性(如果需要)动态地将下拉列表中的数据源属性设置为所需的源。
答案 2 :(得分: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);
}
}
}