您的位置: 首页 > 技术文档 > 网络编程 > 数据对象类表单自动绑定
GSSY流程图 回到列表 珊瑚虫IP库浅析
 数据对象类表单自动绑定

作者:martin0728 时间: 2006-12-27 文档类型:翻译 来自:蓝色理想

DarkangleFormBinder

本文附带的代码在Asp.Net 2.0下面调试通过

先讲一下背景

在.Net多层结构程序中,我们会使用一些O/R MAPPING的工具将数据库表或视图映射成实体数据模形用于封装数据,开发中我们可能经常会写这样的代码,例如,我们有一个Student的表,包含一些字段,如Name, Sex, Age, Grade, Height, Weight, ChooseClass.....

我们假设有一个录入学生信息的表单,我们可能会写这样的一些代码,在前台上:

姓名:<asp:TextBox ID="Name" runat="Server" />
年龄:<asp:TextBox ID="Age" runat = "Server" />
年级:<aspropDownList ID="Grade" runat = "server" />
课外活动: <asp:CheckBoxList ID="ChooseClass" runat= "server" />

后台呢:

我们需要先构造一个新的对象:

Student s= new Student();

然后设置它的属性:

s.Name = Name.Text;
s.Age = Age.Text;
s.Grade = Grade.SelectedValue;

然后保存到后台数据库

如果是读取一条记录出来显示在页面上,我们可能先要取得一个对象实例:

Student s = bll.GetStudentById(id);
Name.Text = s.Name;
Age.Text = s.Age;
Grade.Items.FindByValue(s.Grade).Selected = true;

上面标红的部分代码可能会非常多,尤其是在字段比较多的时候,设定这些值就非常麻烦,不但不能漏掉,还要做类型转换等,稍有不小心就会出错.

现在我们可以利用反射的方法将这些属性自动与控件值关联起来,这样就不用手动地编写这些代码了.

具体内容请看我的示例工程文件.注意要在Web.Config中加上控件的引用路径.

这些代码参考了MSDN上面的内容,但是原来的代码有BUG,并且不支持可以多项选择的控件.我在这里加入了两个控件,分别是DarkangleCheckBoxList和DarkangleListBox 这两个控件支持将多项选择的属性以逗号分开的方式存储于数据库字段中.  比如,学生.课余活动 = "照象,游泳,足球",不需要写额外的代码即可直接绑定到多项选择控件.

目前支持的绑定控件有:Label,TextBox,CheckBox,DarkangleCheckBoxList,DarkangleListBox(如果您只需要单项选择,则可以使用自带的ListBox控件),ListBox,DropDownList, RadioButton,RadioButtonList,日历控件.

希望我写的东西对您的开发有所帮助.

Good luck~~~~;)

源代码与示例打包下载

应版主大人要求,把源码贴出来的,其实我提供的下载包里面是有源码的,就在类工程里面,随便也把原来那个老外的也帖上来,我修改了部分内容,原来那个代码运行起来也是有问题的。

先帖我的:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Reflection;

namespace Darkangle
{
    public class FormBinder
    {
        public static void BindObjectToControls(object obj, Control container)
        {
            if (obj == null) return;
            Type objType = obj.GetType();
            PropertyInfo[] objPropertiesArray = objType.GetProperties();
            foreach (PropertyInfo objProperty in objPropertiesArray)
            {
                Control control = container.FindControl(objProperty.Name);
                bool success = false;
                bool isCustom = false;
                if (control is DarkangleListBox)
                {
                    DarkangleListBox listBox = (DarkangleListBox)control;
                    string propertyValue = objProperty.GetValue(obj, null).ToString();
                    listBox.SetListValue(propertyValue);
                    isCustom = true;
                }
                if (control is DarkangleCheckBoxList)
                {
                    DarkangleCheckBoxList checkBoxList = (DarkangleCheckBoxList)control;
                    string propertyValue = objProperty.GetValue(obj, null).ToString();
                    checkBoxList.SetListValue(propertyValue);
                    isCustom = true;
                }
                if (!isCustom)
                {
                    if (control is ListControl)
                    {
                        ListControl listControl = (ListControl)control;
                        string propertyValue = objProperty.GetValue(obj, null).ToString();
                        ListItem listItem = listControl.Items.FindByValue(propertyValue);
                        if (listItem != null) listItem.Selected = true;
                    }
                    else
                    {
                        Type controlType = control.GetType();
                        PropertyInfo[] controlPropertiesArray = controlType.GetProperties();
                        success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Checked", typeof(bool));
                        if (!success)
                        {
                            success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "SelectedDate", typeof(DateTime));
                            if (success)
                                FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "VisibleDate", typeof(DateTime));
                        }
                        if (!success)
                            success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Value", typeof(String));
                        if (!success)
                            success = FindAndSetControlProperty(obj, objProperty, control, controlPropertiesArray, "Text", typeof(String));
                    }
                }
            }
        }
        private static bool FindAndSetControlProperty(object obj, PropertyInfo objProperty, Control control, PropertyInfo[] controlPropertiesArray, string propertyName, Type type)
        {
            foreach (PropertyInfo controlProperty in controlPropertiesArray)
            {
                if (controlProperty.Name == propertyName && controlProperty.PropertyType == type)
                {
                    controlProperty.SetValue(control, Convert.ChangeType(objProperty.GetValue(obj, null), type), null);
                    return true;
                }
            }
            return false;
        }
        public static void BindControlsToObject(object obj, Control container)
        {
            if (obj == null) return;
            Type objType = obj.GetType();
            PropertyInfo[] objPropertiesArray = objType.GetProperties();
            foreach (PropertyInfo objProperty in objPropertiesArray)
            {
                bool success = false;
                bool isCustom = false;
                Control control = container.FindControl(objProperty.Name);
                if (control is DarkangleListBox)
                {
                    DarkangleListBox listBox = (DarkangleListBox)control;
                    if (listBox.SelectedIndex > -1)
                        objProperty.SetValue(obj, Convert.ChangeType(listBox.GetListValue(), objProperty.PropertyType), null);
                    isCustom = true;
                }
                if (control is DarkangleCheckBoxList)
                {
                    DarkangleCheckBoxList checkBoxList = (DarkangleCheckBoxList)control;
                    if (checkBoxList.SelectedIndex > -1)
                        objProperty.SetValue(obj, Convert.ChangeType(checkBoxList.GetListValue(), objProperty.PropertyType), null);
                    isCustom = true;
                }
                if (!isCustom)
                {
                    if (control is ListControl)
                    {
                        ListControl listControl = (ListControl)control;
                        if (listControl.SelectedItem != null)
                            objProperty.SetValue(obj, Convert.ChangeType(listControl.SelectedItem.Value, objProperty.PropertyType), null);
                    }
                    else
                    {
                        Type controlType = control.GetType();
                        PropertyInfo[] controlPropertiesArray = controlType.GetProperties();

                        success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "Checked", typeof(bool));
                        if (!success)
                            success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "SelectedDate", typeof(DateTime));
                        if (!success)
                            success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "Value", typeof(String));
                        if (!success)
                            success = FindAndGetControlProperty(obj, objProperty, control, controlPropertiesArray, "Text", typeof(String));
                    }
                }
            }
        }
        private static bool FindAndGetControlProperty(object obj, PropertyInfo objProperty, Control control, PropertyInfo[] controlPropertiesArray, string propertyName, Type type)
        {
            foreach (PropertyInfo controlProperty in controlPropertiesArray)
            {
                if (controlProperty.Name == propertyName && controlProperty.PropertyType == type)
                {
                    try
                    {
                        objProperty.SetValue(obj, Convert.ChangeType(controlProperty.GetValue(control, null), objProperty.PropertyType), null);
                        return true;
                    }
                    catch
                    {
                        return false;
                    }
                }
            }
            return false;
        }
    }
}

这两个是我护展出来的控件:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;

namespace System.Web.UI.WebControls
{
   
    public class DarkangleCheckBoxList : CheckBoxList
    {
        public void SetListValue(string listValue)
        {
            if (listValue == null || listValue.Trim() == string.Empty)
                return;
            string[] valueList = listValue.Split(new char[] { ',' });
            if (valueList.Length == 0)
                return;
            for (int i = 0; i < valueList.Length; i++)
            {
                if (valueList[i].Length != 0 && valueList[i] != string.Empty)
                    this.Items.FindByValue(valueList[i]).Selected = true;
            }
        }
        public string GetListValue()
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < this.Items.Count; i++)
            {
                if (this.Items[i].Selected)
                    sb.Append(this.Items[i].Value + ",");
            }
            return sb.Remove(sb.Length - 1, 1).ToString();
        }
    }
    public class DarkangleListBox : ListBox
    {
        public void SetListValue(string listValue)
        {
            if (listValue == null || listValue.Trim() == string.Empty)
                return;
            string[] valueList = listValue.Split(new char[] { ',' });
            if (valueList.Length == 0)
                return;
            for (int i = 0; i < valueList.Length; i++)
            {
                if (valueList[i].Length != 0 && valueList[i] != string.Empty)
                    this.Items.FindByValue(valueList[i]).Selected = true;
            }
        }
        public string GetListValue()
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < this.Items.Count; i++)
            {
                if (this.Items[i].Selected)
                    sb.Append(this.Items[i].Value + ",");
            }
            return sb.Remove(sb.Length-1,1).ToString();
        }
    }
}

经典论坛讨论
http://bbs.blueidea.com/thread-2707666-1-1.html

出处:蓝色理想
责任编辑:blue

◎进入论坛网络编程版块参加讨论

相关文章 更多相关链接
数据引起的思考
简洁的表单验证程序
常见可用性错误——表单组件错误
用css制作表单并体验亲和力
SPL3.0数据连接详解
关键字搜索 常规搜索 推荐文档
热门搜索:CSS Fireworks 设计比赛 网页制作 web标准 用户体验 UE photoshop Dreamweaver Studio8 Flash 手绘 CG
站点最新 站点最新列表
周大福“敬•自然”设计大赛开启
国际体验设计大会7月将在京举行
中国国防科技信息中心标志征集
云计算如何让安全问题可控
云计算是多数企业唯一拥抱互联网的机会
阿里行云
云手机年终巨献,送礼标配299起
阿里巴巴CTO王坚的"云和互联网观"
1499元买真八核 云OS双蛋大促
首届COCO桌面手机主题设计大赛
栏目最新 栏目最新列表
浅谈JavaScript编程语言的编码规范
如何在illustrator中绘制台历
Ps简单绘制一个可爱的铅笔图标
数据同步算法研究
用ps作简单的作品展示页面
CSS定位机制之一:普通流
25个最佳最闪亮的Eclipse开发项目
Illustrator中制作针线缝制文字效果
Photoshop制作印刷凹凸字体
VS2010中创建自定义SQL Rule

蓝色理想版权申明:除部分特别声明不要转载,或者授权我站独家播发的文章外,大家可以自由转载我站点的原创文章,但原作者和来自我站的链接必须保留(非我站原创的,按照原来自一节,自行链接)。文章版权归我站和作者共有。

转载要求:转载之图片、文件,链接请不要盗链到本站,且不准打上各自站点的水印,亦不能抹去我站点水印。

特别注意:本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有,文章若有侵犯作者版权,请与我们联系,我们将立即删除修改。

您的评论
用户名:  口令:
说明:输入正确的用户名和密码才能参与评论。如果您不是本站会员,你可以注册 为本站会员。
注意:文章中的链接、内容等需要修改的错误,请用报告错误,以利文档及时修改。
不评分 1 2 3 4 5
注意:请不要在评论中含与内容无关的广告链接,违者封ID
请您注意:
·不良评论请用报告管理员,以利管理员及时删除。
·尊重网上道德,遵守中华人民共和国的各项有关法律法规
·承担一切因您的行为而直接或间接导致的民事或刑事法律责任
·本站评论管理人员有权保留或删除其管辖评论中的任意内容
·您在本站发表的作品,本站有权在网站内转载或引用
·参与本评论即表明您已经阅读并接受上述条款
推荐文档 | 打印文档 | 评论文档 | 报告错误  
专业书推荐 更多内容
网站可用性测试及优化指南
《写给大家看的色彩书1》
《跟我去香港》
众妙之门—网站UI 设计之道
《Flex 4.0 RIA开发宝典》
《赢在设计》
犀利开发—jQuery内核详解与实践
作品集 更多内容

杂⑦杂⑧ Gold NORMANA V2