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

推荐订阅源

Simon Willison's Weblog
Simon Willison's Weblog
P
Privacy International News Feed
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
Troy Hunt's Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
Attack and Defense Labs
Attack and Defense Labs
S
Secure Thoughts
V2EX - 技术
V2EX - 技术
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
O
OpenAI News
Cloudbric
Cloudbric
Google Online Security Blog
Google Online Security Blog
Schneier on Security
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Help Net Security
Help Net Security
Cyberwarzone
Cyberwarzone
G
GRAHAM CLULEY
L
Lohrmann on Cybersecurity
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Spread Privacy
Spread Privacy
NISL@THU
NISL@THU
N
News and Events Feed by Topic
T
Tenable Blog
S
Security @ Cisco Blogs
N
News and Events Feed by Topic
The Hacker News
The Hacker News
C
CXSECURITY Database RSS Feed - CXSecurity.com
宝玉的分享
宝玉的分享
月光博客
月光博客
酷 壳 – CoolShell
酷 壳 – CoolShell
美团技术团队
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
V
Visual Studio Blog
P
Proofpoint News Feed
Webroot Blog
Webroot Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 三生石上(FineUI控件)
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Jina AI
Jina AI
雷峰网
雷峰网
T
The Blog of Author Tim Ferriss
Hugging Face - Blog
Hugging Face - Blog
腾讯CDC
L
LangChain Blog
The Register - Security
The Register - Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东

博客园 - 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