日期:2014-05-19  浏览次数:20567 次

★(50分)动态给控件赋值
动态给控件赋值

        我想制作一个方法(函数),依次传入每一个控件,传入的控件可能是Label,也可能是TextBox,也可能是其他自定义的用户控件,重要的共同点是都有Height、Width等属性。
        再根据需要从数据库提取属性的值后,将值赋给传入控件的Height、Width等属性,应该如何实现该方法呢?

请大家多指点,给源代码做参考的能得更多分,谢谢啦。

------解决方案--------------------
学习啊
------解决方案--------------------
protected void Page_Load(object sender, EventArgs e)
{
System.Web.UI.Control control = new Control();
control = new TextBox();
SetControlProperty(control);


}

private Control SetControlProperty(System.Web.UI.Control control)
{
if (control is TextBox)
{
TextBox tb = (TextBox)control;
tb.Height = Unit.Pixel(80);
}

return tb;

//other contorles are in the same scenarioes.
}
------解决方案--------------------
遍历控件
foreach(Control cs in this.Controls )
{
if (cs is TextBox)
{
cs.Text = "123456789 ";
}
}
------解决方案--------------------
time_is_life的做法本来没错,但太烦琐了,楼主提到了两个属性WebControl都有,而且你自定义的控件也需要继承自WebControl.

下面是代码

假设页面上有一个label和textbox控件

protected void Page_Load(object sender, EventArgs e)
{
WebControl[] controls=new WebControl[]{Label1,TextBox1 };
SetProPerty(controls, "100 ", "100 ");
}
void SetProPerty(WebControl[] controls,string width,string height)
{
foreach (WebControl control in controls)
{
control.Width = Unit.Parse(width);
control.Height = Unit.Parse(height);

}
}