利用封装向页面控件赋值


    一个表中含有N多个字段,如果需要全部显示,你将会怎么做?

如果你还在手动绑定,不觉得太过于烦躁了吗?

   不多说,直接实例:

1 .目标页面:

  

人懒,就3个控件吧.......

 cs代码:

只需要调用 SetModelValueToControl() 方法就行了.

SetModelValueToControl()代码如下:

View Code
 1     ///<summary>
2 ///将 Model对象绑定页面控件
3 ///</summary>
4 ///<param name="model"></param>
5 public void SetModelValueToControl(object model)
6 {
7
8 SetModelValueToControl(model, this);
9
10 }
11 ///<summary>
12 /// 将 Model对象绑定页面控件
13 ///</summary>
14 ///<param name="model">对象</param>
15 ///<param name="parentControl">页面的容器..form1 ,page 等</param>
16 protected void SetModelValueToControl(object model, Control parentControl)
17 {
18 if (model == null) return;
19 Type type = model.GetType();
20 PropertyInfo[] info = type.GetProperties();
21 Control c = null; ;
22 object value=null;
23 foreach (PropertyInfo p in info)
24 {
25 c = checkControl(p.Name, parentControl);
26 if (c != null)
27 {
28 type = c.GetType();
29 if (type.Equals(typeof(TextBox)))
30 {
31 value = p.GetValue(model, null);
32 }
33 if (type.Equals(typeof(DropDownList)))
34 {
35 value = p.GetValue(model, null);
36 }
37
38 BindControlData(type, c, value);
39 }
40
41
42 }
43 }

检查控件是否存在:对应不同的控件,需要不同方式处理.这里您动动脑,自己完成吧!

View Code
 1   ///<summary>
2 /// 检查控件
3 ///</summary>
4 ///<param name="name">字段名,如 txtUsername ,则 传入 Username</param>
5 ///<param name="parentcontrol">目标容器</param>
6 ///<returns></returns>
7 private Control checkControl(string name, Control parentcontrol)
8 {
9 Control c = null; ;
10 if (parentcontrol.FindControl("txt" + name) != null)
11 {
12 c = parentcontrol.FindControl("txt" + name);
13 }
14 if (parentcontrol.FindControl("dlist" + name) != null)
15 {
16 c = parentcontrol.FindControl("dlist" + name);
17 }
18 return c;
19 }

最关键的方法.向页面绑定数据

View Code
 1  ///<summary>
2 /// 向页面绑定数据
3 ///</summary>
4 ///<param name="type"></param>
5 ///<param name="c"></param>
6 ///<param name="value"></param>
7 protected void BindControlData(Type type, Control c, object value)
8 {
9
10 if (type.Equals(typeof(TextBox)))
11 {
12 if (value == null)
13 {
14 value = "";
15 }
16 ((TextBox)c).Text = value.ToString().Trim();
17 }
18 if (type.Equals(typeof(DropDownList)))
19 {
20 DropDownList ddlist = (DropDownList)c;
21 if (value == null)
22 {
23 value = "";
24 ddlist.SelectedIndex = 0;
25 }
26 else
27 {
28 ddlist.ClearSelection();
29 ddlist.Items.Add(value.ToString());
30 }
31 }

成功输出:


源码地址:http://files.cnblogs.com/xyong/Demo_BindControl.zip

 

转载于:https://www.cnblogs.com/xyong/archive/2011/10/28/2227437.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值