是不是有很多人数据绑定都是用this.textbox1.Text=““呢;今天一个小实验,给大家分享一下,该程序使用简单的反射进行数据绑定;
1、新建一个winform应用程序;具体步骤就不详细说了,随便布个局;来张截图先;
2、创建一个userInfo类,
public class userInfo
{
public string username { get; set; }
public string pwd { get; set; }
public string email { get; set; }
public string pwdquestion { get; set; }
public string pwdanswer { get; set; }
public string birthday { get; set; }
public string sex { get; set; }
}
3、在刚才创建的那个窗体的cs代码中收集界面上的数据;然后用一个userInfo实例对象进行保存;具体怎么收集信息,用你们自己的方法吧
4、新建一个窗体ShowInfo
那上面的Label标签一定要命名要和userInfo类中的属性名称一样,这样才能通过反射进行匹配,数据绑定;
修改它的构造函数,并添加DataBind()进行数据绑定
public ShowInfo(userInfo userinfo)
{
InitializeComponent();
DataBind(userinfo);
}
void DataBind(userInfo Info)
{
Type type = Info.GetType();
foreach (Control item in this.Controls)
{
PropertyInfo[] infos = type.GetProperties();
foreach (PropertyInfo info in infos)
{
if (item.Name == info.Name)
{
item.Text = info.GetValue(Info, null).ToString();
}
}
}
}
5、好了,剩下的工作,大家知道怎么办了吧;