你型我塑博客

snryang

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  24 随笔 :: 8 文章 :: 29 评论 :: 0 引用

做项目开发的时候,大家应该经常都会遇到一个表里面的很多个字段的情况吧.在之前我接触的一个项目,有一个表有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

posted on 2008-03-22 20:21 snryang 阅读(417) 评论(10)  编辑 收藏 网摘 所属分类: 原创

评论

#1楼  2008-03-24 10:36 getao [未注册用户]
看了 十分感谢分享
  回复  引用    

#2楼  2008-03-25 12:15 Sanney      
csdn上看到了 顶一下
  回复  引用  查看    

#3楼  2008-03-25 12:48 Sanney      
SetDropDownListItem 方法貌似没写出来诶
  回复  引用  查看    

#4楼 [楼主] 2008-03-25 20:32 snryang      
@Sanney
是一个设置下拉列表默认值的方法。相当于
txt_Type.Items.FindByValue(user.Type).Selected=true;
  回复  引用  查看    

好!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  回复  引用    

#6楼  2008-03-30 15:22 stg609      
不错,引用一下
  回复  引用  查看    

#7楼  2008-04-01 16:10 Xproer-松鼠      
稍稍改进了一下
  回复  引用  查看    

#8楼  2008-04-01 16:10 Xproer-松鼠      
protected void Button1_Click(object sender, EventArgs e)
        
{
            
this.GetControlsName(this.Page);
        }


        
void GetControlsName(Control c)
        
{
            ControlCollection cl 
= c.Controls;
            
for (int i = 0, l = cl.Count; i < l; ++i)
            
{
                
if (cl[i].Controls.Count > 0)
                
{
                    
this.GetControlsName(cl[i]);
                }
//此控件有ID
                if (!string.IsNullOrEmpty(cl[i].ID))
                
{
                    Response.Write(cl[i].ID);
                    Response.Write(
"<br>");
                }

            }

        }

  回复  引用  查看    

#9楼 [楼主] 2008-04-01 19:50 snryang      
@Xproer-松鼠
将页面上的控件放在一个Panel里面,就可以只查Panel里面的控件,不用递归。
  回复  引用  查看    

#10楼  2008-05-05 13:34 willieQ      
学习~~~正是需要的!!!
  回复  引用  查看    


标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-03-26 20:58 编辑过
"五向定位"职业成长路线公开课(上海、南京、大连)
Google站内搜索


相关链接: