热门:网页模板.net视频教程JQueryMVCjsonExtJs源码示例三级联动JQuery菜单
您现在的位置:.Net中文社区>> .Net编程>>正文内容

用反射来解决字段多带来的烦恼

发布时间:2010年05月17日点击数: 佚名

做项目开发的时候,大家应该经常都会遇到一个表里面的很多个字段的情况吧.在之前我接触的一个项目,有一个表有20多个字段.要向表中添加记录,和将一条数据绑定到页面上都要写很多代码.如:

下面是一个用户表的添加

  1. User user = new User();  
  2.         user.Name = this.txt_Name.Text;   
  3.         user.Remark = this.txt_Remark.Text;  
  4.         user.Age = int.Parse(this.txt_Age.Text);  
  5.         user.Type=this.txt_Type.SelectedValue;   
  6.         user.Time=DateTime.Parse(this.txt_Time.Text);  
  7.         new Test().SaveOrUpdate(user);  

将表里面的数据绑定到控件里面如下 

  1. User user=(User) new test().Get(typeof(User),"1");  
  2. txt_Name.Text=user.Name;  
  3. txt_Remark.Text=user.Remark;  
  4. txt_Age.Text=user.Age.ToString();  
  5. txt_Type.SelectedValue=txt_Type.Items.FindByValue(user.Type);  
  6. txt_Time.Text=User.Time.ToString("yyyy-MM-dd");  

上面的列子,数据类型不对我们得进行转换,下拉列表还要进行绑定.当然字段比较少,还不容易怎么出错,如果字段多了,这样一个一个的写太老火了,而且还容易忘记一些,或者把一些数据绑定错,或者忘了ToString().

思路是这样的:
一、对于网页中控件的命名规为 "txt_实体类的字段名";
二、遍历页面中的所有控件,使用反射将控件的值赋给对象。和将对象的属性值绑定到控件上。

下面是要用到的一些方法  

  1. /**////  <summary>  
  2. /// 字符串首字母大写  
  3. ///  </summary>  
  4. ///  <param name="s"> </param>  
  5. ///  <returns> </returns>  
  6. public static string ToProperCase(string s)  
  7. {  
  8.     string revised = "";  
  9.     if (s.Length > 0)  
  10.     {  
  11.         revised = s.Trim();  
  12.         revised = revised.Substring(0, 1).ToUpper() + revised.Substring(1).ToLower();  
  13.     }  
  14.     return revised;  
  15. }  
  16.  
  17. /**////  <summary>  
  18. /// 设置对象属性的值  
  19. ///  </summary>  
  20. public static void SetProperty(object obj, string name, object value)  
  21. {  
  22.     PropertyInfo propertyInfo = obj.GetType().GetProperty(name);  
  23.     object objValue = Convert.ChangeType(value, propertyInfo.PropertyType);  
  24.     propertyInfo.SetValue(obj, objValue, null);  
  25. }  
  26.   
  27. /**////  <summary>  
  28. /// 获取对象属性的值  
  29. ///  </summary>  
  30. public static object GetProperty(object obj, string name)  
  31. {  
  32.     //bindingFlags  
  33.     PropertyInfo propertyInfo = obj.GetType().GetProperty(name);  
  34.     return propertyInfo.GetValue(obj, null);  
  35. }  

将控件的值绑定到对象上面。 

  1.      for (int i = 0; i  < Page.Controls.Count; i++)  
  2.     {  
  3.         SetControlValue(Controls[i], "txt_",ref user);    
  4.     }  
  5. /**////  <summary>  
  6. /// 设置对象的值  
  7. ///  </summary>  
  8. private void SetObjectValue(Control page, string str,ref object obj)  
  9. {  
  10.     foreach (Control content in page.Controls)  
  11.     {  
  12.         if (content.Controls.Count > 0)  
  13.         {  
  14.             SetObjectValue(content, str,ref obj);  
  15.         }  
  16.         if (content.ID != null)  
  17.          {  
  18.              string contentID = content.ID.ToLower();  
  19.             if (contentID.Replace(str, "") != contentID.ToLower())  
  20.             {  
  21.                 SetProperty(obj, ToProperCase(contentID.Replace(str, "")),  
  22.                                                GetProperty(content,"Text")  
  23.                                            );  
  24.             }  
  25.         }  
  26.     }  
  27. }  

(上面的Text是TextBox控件的属性,对于下拉列表框也可以使用这个属性获取选定项的值,所以就不用去判断了,最开始我还去判断类型:)

将对象的值绑定到控件上面  

  1.         for (int i = 0; i  < Page.Controls.Count; i++)  
  2.         {  
  3.             SetControlValue(Controls[i], "txt_", user);  
  4.         }  
  5.  
  6. /**////  <summary>  
  7.     /// 设置控件的值  
  8.     ///  </summary>  
  9.     private void SetControlValue(Control page, string str, object obj)  
  10.     {  
  11.         foreach (Control content in page.Controls)  
  12.         {  
  13.             if (content.Controls.Count > 0)  
  14.             {  
  15.                 SetControlValue(content, str, obj);  
  16.             }  
  17.             if (content.ID != null)  
  18.             {  
  19.                 string contentID = content.ID.ToLower();  
  20.                 if (contentID.Replace(str, "") != contentID.ToLower())  
  21.                 {  
  22.                     if (content.GetType() != typeof(DropDownList))  
  23.                     {  
  24.                         SetProperty(content, "Text",  
  25.                                                     GetProperty(obj, ToProperCase(contentID.Replace(str, "")))  
  26.                                                    );  
  27.                     }  
  28.                     else  
  29.                     {  
  30.                         SetDropDownListItem((DropDownList)content, (string)ReflectionUtil.GetProperty(obj, ToProperCase(contentID.Replace(str, "")))); 
  31.                     }  
  32.                 }  
  33.             }  
  34.         }   
  35.     }  

本站热点业务

更多模板/案例展示

关于我们 | 联系我们 | 团队日志 | 网站地图 | 网站合作