下面是一個用戶表的添加
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>
/// <param name="s"></param>
/// <returns></returns>
public static string ToProperCase(string s)
{
string revised = "";
if (s.Length > 0)
{
revised = s.Trim();
revised = revised.Substring(0, 1).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);
}
將控件的值綁定到對象上面。
{
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控件的屬性,對於下拉列表框也可以使用這個屬性獲取選定項的值,所以就不用去判斷了,最開始我還去判斷類型:)
將對象的值綁定到控件上面
{
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, ""))));
}
}
}
}
}
主要的代碼就上面這些,你可以將這些放到公用的類庫裏,以後遇到字段多的表我們也就不用怕了.