惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
Docker
Simon Willison's Weblog
Simon Willison's Weblog
H
Help Net Security
F
Fortinet All Blogs
H
Heimdal Security Blog
S
Schneier on Security
L
LangChain Blog
博客园 - Franky
酷 壳 – CoolShell
酷 壳 – CoolShell
NISL@THU
NISL@THU
P
Palo Alto Networks Blog
J
Java Code Geeks
博客园 - 【当耐特】
The Last Watchdog
The Last Watchdog
W
WeLiveSecurity
www.infosecurity-magazine.com
www.infosecurity-magazine.com
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
Vulnerabilities – Threatpost
I
InfoQ
Recorded Future
Recorded Future
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
C
CERT Recently Published Vulnerability Notes
T
Tenable Blog
腾讯CDC
C
Check Point Blog
量子位
M
MIT News - Artificial intelligence
GbyAI
GbyAI
罗磊的独立博客
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
B
Blog
小众软件
小众软件
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
C
CXSECURITY Database RSS Feed - CXSecurity.com
Stack Overflow Blog
Stack Overflow Blog
P
Proofpoint News Feed
P
Privacy & Cybersecurity Law Blog
V2EX - 技术
V2EX - 技术
T
Threatpost
Engineering at Meta
Engineering at Meta
Attack and Defense Labs
Attack and Defense Labs
T
Tailwind CSS Blog
S
Securelist
The Cloudflare Blog
博客园 - 叶小钗
L
LINUX DO - 最新话题
T
Troy Hunt's Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
爱范儿
爱范儿

博客园 - snryang

网站发布小工具,--让发布变简单一点 - snryang - 博客园 鼠标右键发布文件到远程服务器 关于跑步耳机的一些思考 对棋牌游戏平台的一些思考 复杂业务简单化的一个小技巧 老婆和老媽同時掉在了水裡终于有答案了 重发我的 HTML单据输入控件 js对象序列化为json字符串 CSS的一个小技巧 - snryang - 博客园 基于jQuery的单据输入 基于jQuery的表单验证 - snryang - 博客园 基于JQuery的拖拉效果, cms系统也不复杂 IList对象排序方法 基于jqury的自动完成 让你的博客园变灰 弹出遮罩层示例. Jquery学习 数据库结构中的"树"
用反射来解决字段多带来的烦恼
snryang · 2008-03-22 · via 博客园 - snryang

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

2008-03-22 20:21  snryang  阅读(1334)  评论()    收藏  举报

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

下面是一个用户表的添加

        User user = new User();
        user.Name = this.txt_Name.Text; 
        user.Remark = this.txt_Remark.Text;
        user.Age = int.Parse(this.txt_Age.Text);
        user.Type=this.txt_Type.SelectedValue
        user.Time=DateTime.Parse(this.txt_Time.Text);
        new Test().SaveOrUpdate(user);
将表里面的数据绑定到控件里面如下
        User user=(User) new test().Get(typeof(User),"1");
        txt_Name.Text=user.Name;
        txt_Remark.Text=user.Remark;
        txt_Age.Text=user.Age.ToString();
        txt_Type.Items.FindByValue(user.Type).Selected=true;
        txt_Time.Text=User.Time.ToString("yyyy-MM-dd");
上面的列子,数据类型不对我们得进行转换,下拉列表还要进行绑定.当然字段比较少,还不容易怎么出错,如果字段多了,这样一个一个的写太老火了,而且还容易忘记一些,或者把一些数据绑定错,或者忘了ToString().

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

下面是要用到的一些方法

    /// <summary>
    
/// 字符串首字母大写
    
/// </summary>
    
/// <param name="s"></param>
    
/// <returns></returns>

    public static string ToProperCase(string s)
    
{
        
string revised = "";
        
if (s.Length > 0)
        
{
            revised 
= s.Trim();
            revised 
= revised.Substring(01).ToUpper() + revised.Substring(1).ToLower();
        }

        
return revised;
    }


    
/// <summary>
    
/// 设置对象属性的值
    
/// </summary>

    public static void SetProperty(object obj, string name, object value)
    
{
        PropertyInfo propertyInfo 
= obj.GetType().GetProperty(name);
        
object objValue = Convert.ChangeType(value, propertyInfo.PropertyType);
        propertyInfo.SetValue(obj, objValue, 
null);
    }

    
    
/// <summary>
    
/// 获取对象属性的值
    
/// </summary>

    public static object GetProperty(object obj, string name)
    
{
        
//bindingFlags
        PropertyInfo propertyInfo = obj.GetType().GetProperty(name);
        
return propertyInfo.GetValue(obj, null);
    }

         for (int i = 0; i < Page.Controls.Count; i++)
        
{
            SetControlValue(Controls[i], 
"txt_",ref user);  
        }

    
/// <summary>
    
/// 设置对象的值
    
/// </summary>

    private void SetObjectValue(Control page, string str,ref object obj)
    
{
        
foreach (Control content in page.Controls)
        
{
            
if (content.Controls.Count > 0)
            
{
                SetObjectValue(content, str,
ref obj);
            }

            
if (content.ID != null)
             
{
                 
string contentID = content.ID.ToLower();
                
if (contentID.Replace(str, ""!= contentID.ToLower())
                
{
                    SetProperty(obj, ToProperCase(contentID.Replace(str, 
"")),
                                                   GetProperty(content,
"Text")
                                               );
                }

            }

        }

    }

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

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

        for (int i = 0; i < Page.Controls.Count; i++)
        
{
            SetControlValue(Controls[i], 
"txt_", user);
        }


/// <summary>
    
/// 设置控件的值
    
/// </summary>

    private void SetControlValue(Control page, string str, object obj)
    
{
        
foreach (Control content in page.Controls)
        
{
            
if (content.Controls.Count > 0)
            
{
                SetControlValue(content, str, obj);
            }

            
if (content.ID != null)
            
{
                
string contentID = content.ID.ToLower();
                
if (contentID.Replace(str, ""!= contentID.ToLower())
                
{
                    
if (content.GetType() != typeof(DropDownList))
                    
{
                        SetProperty(content, 
"Text",
                                                    GetProperty(obj, ToProperCase(contentID.Replace(str, 
"")))
                                                   );
                    }

                    
else
                    
{
                        SetDropDownListItem((DropDownList)content, (
string)ReflectionUtil.GetProperty(obj, ToProperCase(contentID.Replace(str, ""))));
                    }

                }

            }

        }
 
    }


主要的代码就上面这些,你可以将这些放到公用的类库里,以后遇到字段多的表我们也就不用怕了.
示例下载:/Files/snryang/Demo.rar