利用封装向页面控件赋值


    一个表中含有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 }

成功输出:


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


作者:javaoraspx
出处:http://www.cnblogs.com/xyong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/xyong/p/2227437.html