Visual Studio根據表結構自動生成查詢畫面和C#代碼
原理:
1.通過C#編寫VS的插件;調用VS的設計器;創建控件和代碼
2.SQL代碼通過正規表達式解析出查詢條件並生成控件
3.通過SQL代碼獲得查詢的DataTable並獲得DataColumn;並創建Grid
具體代碼如下
IDesignerHost host;VS設計器的host
Form forhm = (Form)host.RootComponent; 獲得設計器的界面
創建控件兩種方法:
1.通過C#的動態創建控件(如:new Button())
PropertyDescriptor poss; Button btn1 = new Button(); btn1.Name = "btn_OK"; btn1.Text = "查詢"; btn1.Size = new System.Drawing.Size(100, 33); btn1.Location = new System.Drawing.Point(662, (Line + 1) * 10 + (Line + 1) * 21 + 10); pl1.Controls.Add(btn1); forhm.Container.Add(btn1); poss = TypeDescriptor.GetProperties(btn1).Find("Name", true); poss.SetValue(btn1, "btn_OK");
2.通過反射動態創建控件
Control cl = (Control)Assembly.LoadFrom(compath).CreateInstance(ClassName); cl.Location = new System.Drawing.Point(0, y); cl.Name = "AAAA"; cl.RightToLeft = System.Windows.Forms.RightToLeft.No; cl.Size = new System.Drawing.Size(120, 21); cl.Location = new System.Drawing.Point(70 + 70 + ColV * 220 - cl.Size.Width - 5, (LineV + 1) * 10 + LineV * 20 + 5); form.Container.Add(cl); PropertyDescriptor pop = TypeDescriptor.GetProperties(cl).Find("Parent", true); pop.SetValue(cl, form); PropertyDescriptor valu = TypeDescriptor.GetProperties(cl).Find("Name", true); valu.SetValue(cl, ClassName_Start + rd[1].ToString());
動態創建代碼
public static DTE AplictionDTE; Document activeDocument = AplictionDTE.ActiveDocument; ProjectItem projectItem = activeDocument.ProjectItem; FileCodeModel fileCodeModel = projectItem.FileCodeModel; CodeElements codeElements = fileCodeModel.CodeElements; TextSelection ts = (TextSelection)Connect.AplictionDTE.ActiveDocument.Selection; EditPoint ep = ts.ActivePoint.CreateEditPoint(); ep.Insert(" InitControl();\r\n"); ep.Insert(" btn_Cancel.Click += new EventHandler(btn_Cancel_Click);\r\n"); ep.Insert("\r\n");
注意:
創建控件前需要將此控件的使用到的DLL引用到VS的項目中
運行截圖如下:
1.VS的原始設計界面
2.啟動VS插件並設置SQL語句
3.設置SQL的條件的名稱
4.自動生成的界面
5.自動生成的C#代碼