畢業設計結束了,在設計工程中的一些難點記錄下來,以供往後查閱。這次畢業設計winform應用程序。爲了在開發過程當中提升開發的效率,特此設立了幾個工具類。sql
1、數據庫中表字段自動生成實體類數據庫
在數據庫中進行表結構設計以後,爲今生成實體類,代碼以下。ide
/// <summary> /// 用於從數據庫中生成實體類 /// </summary> public class ProduceEntity { private string tableName; public ProduceEntity(string tableName) { this.tableName = tableName; } // string strconn = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString; string strconn = string.Format(@"Data Source=(local);Initial Catalog=GraduationProject;User ID=sa;Password=123"); public void StartProduceEntity() { // string tableName = "QCZZ"; List<string> ZD = new List<string>(); List<string> type = new List<string>(); string sql=string.Format("SELECT a.name,b.name FROM syscolumns a left JOIN systypes b on a.xusertype=b.xusertype WHERE a.id=OBJECT_ID('{0}')",tableName); //using () //{ SqlConnection conn = new SqlConnection(strconn); SqlCommand cmd = new SqlCommand(sql,conn); try { conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { ZD.Add(reader[0].ToString()); type.Add(reader[1].ToString()); } } ProcessProduceEntity(ZD, type,tableName); } catch (Exception e2) { } finally { conn.Close(); } } // } private void ProcessProduceEntity(List<string> ZD, List<string> type,string tableName) { //string path = string.Format(@"F:\資料\net\C#\Demo\畢業設計\Model\{0}.cs",tableName); string path = string.Format(@"F:\學習資料\畢業設計\Model\{0}.cs", tableName); FileStream fs = new FileStream(path,FileMode.Create); StreamWriter sw = new StreamWriter(fs); StringBuilder sb = new StringBuilder(); sb.Append("using System;\r\n using System.Collections.Generic;\r\n using System.Text;\r\n"); sb.Append("namespace Model\r\n{\r\n"); sb.AppendFormat("public class {0}\r\n", tableName); sb.Append("{\r\n"); string DataType=string.Empty; for(int i=0;i<ZD.Count;i++) { if(type[i].ToLower()=="varchar") { DataType = "string"; //sb.AppendFormat("public string {0}\r\n", ZD[i].ToUpper()); } else if (type[i].ToLower() == "datetime") { DataType = "DateTime"; //sb.AppendFormat("public DateTime {0}\r\n", ZD[i].ToUpper()); } else if (type[i].ToLower() == "int32") { DataType = "int"; } sb.AppendFormat("public {0} {1}\r\n", DataType,ZD[i]); sb.Append("{ \r\n"); sb.Append("set;get;\r\n"); sb.Append("}\r\n"); } sb.Append("}\r\n"); sb.Append("}\r\n"); #region TRY try { sw.Write(sb.ToString()); } catch (Exception E2) { } finally { sw.Close(); fs.Close(); } #endregion } }
這次代碼設計的比較倉促,還存在少量的bug。之後使用時要改正。工具
2、form表單的數據自動加載到實體類中學習
適用於的場景以下表單上一些textbox、RichTextBox等的值自動加載到實體類中,避免了一一的賦值,提升了開發效率。使用前的規則:表單控件的Name屬性必須與實體類中的字段的名稱保持一致。代碼以下所示:ui
1 /// <summary> 2 /// 表單數據生成實體類 3 /// </summary> 4 class FormDataToObject 5 { 6 private List<Control> list = new List<Control>(); 7 /// <summary> 8 /// 卡片類, 9 /// </summary> 10 /// <param name="obj"></param> 11 /// <param name="form"></param> 12 /// <returns></returns> 13 public object FormDataToEntity(object obj,Control form) 14 { 15 try 16 { 17 this.GetControls(form); 18 Type Type = obj.GetType(); 19 20 PropertyInfo[] infos = Type.GetProperties(); 21 //for (int i = 0; i < form.Controls.Count; i++) 22 foreach (Control control in list) 23 { 24 foreach (PropertyInfo info in infos) 25 { 26 if (info.Name == control.Name) 27 { 28 if (typeof(TextBox) == control.GetType()) 29 { 30 info.SetValue(obj, ((TextBox)control).Text, null); 31 } 32 else if (typeof(RadioButton) == control.GetType()) 33 { 34 RadioButton rb = (RadioButton)control; 35 if (rb.Checked) 36 { 37 info.SetValue(obj, true, null); 38 } 39 else 40 { 41 info.SetValue(obj, false, null); 42 } 43 } 44 else if (typeof(DateTimePicker) == control.GetType()) 45 { 46 DateTimePicker dtp = (DateTimePicker)control; 47 DateTime dt = dtp.Value; 48 //int dd = dt.Day; 49 info.SetValue(obj, dt, null); 50 } 51 else if (typeof(ComboBox) == control.GetType()) 52 { 53 ComboBox cbm = (ComboBox)control; 54 info.SetValue(obj, cbm.Text, null); 55 } 56 else if (typeof(RichTextBox) == control.GetType()) 57 { 58 RichTextBox rtb = (RichTextBox)control; 59 info.SetValue(obj, rtb.Text, null); 60 } 61 else if (typeof(NumericUpDown) == control.GetType()) 62 { 63 NumericUpDown num = (NumericUpDown)control; 64 info.SetValue(obj, num.Value, null); 65 } 66 else if (typeof(CheckBox) == control.GetType()) 67 { 68 CheckBox cb = control as CheckBox; 69 if (cb.Checked == true) 70 { 71 info.SetValue(obj, true, null); 72 } 73 } 74 75 } 76 77 } 78 } 79 } 80 catch (Exception e) 81 { 82 MessageBox.Show(e.Message); 83 } 84 return obj; 85 } 86 /// <summary> 87 /// 列表類(不支持批量) 88 /// </summary> 89 /// <param name="obj">實體類</param> 90 /// <param name="dataGridView">DataGridVIew的對象</param> 91 /// <returns></returns> 92 public object FormDataToEntityList(object obj, Control dataGridView) 93 { 94 //this.GetControls(form); 95 Type Type = obj.GetType(); 96 97 PropertyInfo[] infos = Type.GetProperties(); 98 99 if (dataGridView.GetType() == typeof(DataGridView)) 100 { 101 DataGridView dgv= dataGridView as DataGridView; 102 foreach(DataGridViewRow row in dgv.Rows ) 103 foreach(DataGridViewColumn column in dgv.Columns) 104 foreach (PropertyInfo info in infos) 105 { 106 if (info.PropertyType.Name.ToLower() == "int32") 107 { 108 if (info.Name == column.Name) 109 { 110 int value = Convert.ToInt32(row.Cells[column.Name].Value); 111 info.SetValue(obj, value, null); 112 113 } 114 } 115 else 116 { 117 if (info.Name == column.Name) 118 { 119 info.SetValue(obj, row.Cells[column.Name].Value, null); 120 121 } 122 } 123 124 } 125 } 126 127 return obj; 128 } 129 130 private void GetControls(Control Parent) 131 { 132 foreach (Control c in Parent.Controls) 133 { 134 list.Add(c); 135 if (c.Controls.Count > 0) 136 { 137 GetControls(c); 138 } 139 140 } 141 //return list; 142 } 143 }
設計思路:1.經過遞歸方法獲取表單上的所有控件。this
2.經過反射來獲取實體類中的字段信息(Type Type = obj.GetType();PropertyInfo[] infos = Type.GetProperties();)spa
3經過控制實體類中字段與表單控件Name屬性是否一致來進行賦值。設計
3、實體類中的數據自動展示在form表單控件上code
適用於的場景以下實體類中字段的數值自動加載到表單上一些textbox、RichTextBox等中,避免了一一的賦值,提升了開發效率。使用前的規則:表單控件的Name屬性必須與實體類中的字段的名稱保持一致。代碼以下所示:
1 /// <summary> 2 /// 轉換器,從實體類向表單數據 3 /// </summary> 4 class EntityToFormData 5 { 6 #region 用於將實體類中的數據裝換到表單卡片上 7 private static List<Control> list = new List<Control>(); 8 public static void ConvertEntityToForm(object obj,Control form) 9 { 10 Type type = obj.GetType(); 11 PropertyInfo[] infos=type.GetProperties(); 12 GetAllControl(form); 13 foreach (Control c in list) 14 { 15 foreach (PropertyInfo info in infos) 16 { 17 if(c.GetType()==typeof(TextBox) 18 || c.GetType() == typeof(RichTextBox)) 19 if (c.Name == info.Name) 20 { 21 c.Text = info.GetValue(obj, null).ToString(); 22 } 23 if (c.GetType() == typeof(CheckBox)) 24 if (c.Name == info.Name) 25 { 26 bool flag = Convert.ToBoolean(info.GetValue(obj, null)); 27 (c as CheckBox).Checked = flag; 28 } 29 if(c.GetType()==typeof(NumericUpDown)) 30 { 31 if (c.Name == info.Name) 32 { 33 decimal b = Convert.ToDecimal(info.GetValue(obj, null)); 34 (c as NumericUpDown).Value = b; 35 } 36 } 37 } 38 } 39 } 40 //用於獲取表單上的全部控件aa 41 private static void GetAllControl(Control control) 42 { 43 foreach(Control c in control.Controls) 44 { 45 list.Add(c); 46 if (c.Controls.Count > 0) 47 { 48 GetAllControl(c); 49 } 50 51 52 } 53 } 54 #endregion 55 56 #region 用於將實體類中的數據轉換到表單列表上 57 /// <summary> 58 /// 59 /// </summary> 60 /// <param name="obj">實體類</param> 61 /// <param name="dgv">列表DataGridView實例</param> 62 public static void ConvertEntityToFormList(object obj, DataGridView dgv) 63 { 64 Type type = obj.GetType(); 65 PropertyInfo[] infos = type.GetProperties(); 66 int index = dgv.Rows.Add(); 67 foreach (DataGridViewColumn column in dgv.Columns) 68 foreach (PropertyInfo info in infos) 69 { 70 71 if (info.Name == column.Name) 72 { 73 dgv.Rows[index].Cells[column.Name].Value = info.GetValue(obj, null); 74 } 75 } 76 dgv.Rows[index].Tag = obj; 77 } 78 #endregion 79 }