思路:
1、想想插入语句,大概是这样的一个框架:INSERT INTO 表名 (数据库列名) values (值)
2、这里要3个变量是不固定的,分别是:表名、数据库列名、值;
a.表名我们这里很容易可以获取到
b.数据库列名,我们可以遍历容器获取控件的Name属性
c.值,我们可以遍历容器获取控件的Text属性
1 private static Dictionary<string, string> GetDicKeyValue(Control controlBox) 2 { 3 //遍历容器获取控件的Name属性和Text属性,存放到键值中,用于以下的拼接sql 4 Dictionary<string, string> dic = new Dictionary<string, string>(); 5 foreach (Control item in controlBox.Controls) 6 { 7 if (item is Label || item is PictureBox) 8 { 9 continue; 10 } 11 if (item is TextBox) 12 { 13 dic.Add(item.Name.Substring(3, item.Name.Length - 3), item.Text.Trim()); 14 continue; 15 } 16 if (item is ComboBox) 17 { 18 dic.Add(item.Name.Substring(3, item.Name.Length - 3), item.Text); 19 continue; 20 } 21 if (item is DateTimePicker) 22 { 23 dic.Add(item.Name.Substring(3, item.Name.Length - 3), item.Text); 24 continue; 25 } 26 if (item is CheckBox) 27 { 28 string result = ((CheckBox)item).Checked ? "1" : "0"; 29 dic.Add(item.Name.Substring(3, item.Name.Length - 3), result); 30 continue; 31 } 32 } 33 return dic; 34 }
好了,我们通过上面一个函数已经获取到控件的Name属性(即数据库列名)和Text属性(即值),下面开始组装Sql语句
1 private void button1_Click(object sender, EventArgs e) 2 { 3 Dictionary<string, string> dic = GetDicKeyValue(panel1); 4 string autoMatchSql = string.Empty; 5 StringBuilder Sb1 = new StringBuilder(); 6 StringBuilder Sb2 = new StringBuilder(); 7 foreach (KeyValuePair<string, string> item in dic) 8 { 9 Sb1.Append(item.Key.Trim()).Append(","); 10 Sb2.Append("‘").Append(item.Value.Trim()).Append("‘").Append(","); 11 } 12 autoMatchSql += "INSERT INTO 表名 "; 13 autoMatchSql += " (" + Sb1.ToString().Substring(0, Sb1.Length - 1) + ") VALUES "; 14 autoMatchSql += " (" + Sb2.ToString().Substring(0, Sb2.Length - 1) + ")"; 15 }
原文地址:https://www.cnblogs.com/chenyanbin/p/10201465.html
时间: 2024-10-13 01:23:03