码迷,mamicode.com
首页 > 其他好文 > 详细

毕设之工具类构建

时间:2015-06-18 13:03:49      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:

      毕业设计结束了,在设计工程中的一些难点记录下来,以供日后查阅。此次毕业设计winform应用程序。为了在开发过程中提高开发的效率,特此设立了几个工具类。

一、数据库中表字段自动生成实体类

在数据库中进行表结构设计之后,为此生成实体类,代码如下。

技术分享
  /// <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
        }

       
    }
View Code

此次代码设计的比较仓促,还存在少许的bug。以后使用时要改正。

二、form表单的数据自动加载到实体类中

      适用于的场景如下表单上一些textbox、RichTextBox等的值自动加载到实体类中,避免了一一的赋值,提高了开发效率。使用前的规则:表单控件的Name属性必须与实体类中的字段的名称保持一致。代码如下所示:

技术分享
  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     }
View Code

设计思路:1.通过递归方法获取表单上的全部控件。

2.通过反射来获取实体类中的字段信息(Type Type = obj.GetType();PropertyInfo[] infos = Type.GetProperties();)

3通过控制实体类中字段与表单控件Name属性是否一致来进行赋值。

 三、实体类中的数据自动展现在form表单控件上

       适用于的场景如下实体类中字段的数值自动加载到表单上一些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     }
View Code

 

毕设之工具类构建

标签:

原文地址:http://www.cnblogs.com/ningfd/p/4585381.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!