自定义对象与控件之间的相互赋值

现在在做的一个需求:根据用户的需要,动态的生成产品的属性,最多50个。要求显示在界面上,并且可以实现对属性内容的添加、删除、修改。这样的话在界面上需要50个textbox(可以是别的自定义控件),来显示每个属性的值,修改之后再保存,这就需要对象与控件之间的相互赋值,前天学到一种方法,非常方便。希望能帮助需要的人。

//将对象的值传给控件

private void GetObjectInfoToControlValue(Object obj, Control control)

{

Type type = obj.GetType();

foreach (Control ctl in control.Controls)

{

foreach (PropertyInfo pi in type.GetProperties())

{

if (pi.Name == ctl.Name)

{

ctl.Text = pi.GetValue(obj, null).ToString();

}

}

}

}

//将控件的值传给对象

private void GetControlValueToObjectInfo(Object obj, Control control)

{

Type type = obj.GetType();

foreach (Control ctl in control.Controls)

{

foreach (PropertyInfo pi in type.GetProperties())

{

if (pi.Name == ctl.Name)

{

pi.SetValue(obj, Convert.ChangeType(ctl.Text,pi.PropertyType), null);

}

}

}

}

 

posted on 2012-02-20 11:32  折翼的天使  阅读(397)  评论(0编辑  收藏  举报