使用CodeSmith根据数据库中的表自动生成WinUI界面(使用TableLayoutPanel布局)的代码.

以下代码在codesmith 4.1.2 2729运行通过.生成的代码可用于VS 2005.

转帖请注明出处.谢谢!

<%--
Name:WinUI Code Generator
Author: Tony Wu
Blog:http://tonyepaper.cnblogs.com/
Description:
--%>
<%@ CodeTemplate Language="C#" TargetLanguage="Text" Src="" Inherits="" Debug="False" Description="Template description here." %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Default="" Optional="False" Category="Table" Description="数据来源的Table" OnChanged="" Editor="" EditorBase="" Serializer="" %>
<%@ Property Name="TabLayPanelRowCount" Type="System.Double" Default="1" Optional="False" Category="" Description="需要生成的界面中TableLayoutPanel的行数" OnChanged="" Editor="" EditorBase="" Serializer="" %>
<%@ Property Name="HaveADatagridView" Type="Boolean" Default="false" Optional="False" Category="" Description="是否包含一个DataGridView用于显示关联表信息" OnChanged="" Editor="" EditorBase="" Serializer="" %>

<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="System.Data" %>

<%@ Import Namespace="SchemaExplorer" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Collections.Generic" %>

This Table have <%=this.SourceTable.Columns.Count%> Columns.
-----------
//======================================================================
//frm<%=this.SourceTable.Name%>.Designer.cs.cs
//======================================================================
namespace MasterSoft.WinUI
{
    partial class frmStockOut
    {
        /// <summary>
        ///
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        ///
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows

        /// <summary>
        ///
        ///
        /// </summary>
        private void InitializeComponent()
        {
<%=InstancePanel()%>
<%=InstanceLable()%>
<%=InstanceControl()%>
            this.SuspendLayout();
<%=InitializeTableLayoutPanel()%>
<%=InitializeLable()%>
<%=InitializeControl()%>
            //
            // frmStockOut
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize =
    new System.Drawing.Size
    (<%=this.TabLayPanelColumnCount()*98%>,
    <%=this.TabLayPanelRowCount*25*(this.HaveADatagridView?1.9:1)%>);
            this.Controls.Add(this.tableLayoutPanel1);
            this.Name = "frmStockOut";
            this.Text = "<%=this.SourceTable.Description%>";
            this.ResumeLayout(false);

        }

        #endregion

<%=DeclarePanelProperty()%>
<%=DeclareLableProperty() %>
<%=DeclareControlProperty()%>
    }
}

//======================================================================
//frm<%=this.SourceTable.Name%>.cs
//======================================================================
<%=UsingNameSpace()%>
namespace MasterSoft.WinUI
{
    public partial class <%=getClassName()%> : IMdiChildEditForm
    {
        BindingSource <%=getBindingSourceName()%> = new BindingSource();
        <%=getBLLClassFullName()%> <%=getBLLPropertyName()%>;
        private static <%=getClassName()%> frm = null;
        public <%=getClassName()%>()
        {
            InitializeComponent();
            <%=getBLLPropertyName()%> = new <%=getBLLClassFullName()%>();
        }
  
        public override IMdiChildEditForm GetInstance()
        {
            if (frm == null || frm.IsDisposed == true)
            {
                frm = new <%=getClassName()%>();
            }
            else
            {
                frm.Activate();
            }
            return frm;
        }  
  
        private void <%=getClassName()%>_Load(object sender, EventArgs e)
        {
<%=BindingData()%>
        }  
        #region IMdiChildEditForm ??

        public override BindingSource BindingSource()
        {
            return <%=this.getBindingSourceName()%>;
        }

        public override MasterSoft.BLL.IEntityBLL getEntityBLL()
        {
            return <%=this.getBLLPropertyName()%>;
        }

        #endregion
 }

<script runat="template">
// 换行

public const string Enter="\t\n";

//制表符
const string Tab="\t";

//两个制表符的缩进
const string Indent2=Tab+Tab;

//三个制表符的缩进
const string Indent3=Indent2+Tab;

//外键信息
Dictionary<ColumnSchema,TableKeySchema> fKDict;
#region Pascal命名
public string ToPascal(string s)
{
 return s.Substring(0,1).ToUpper()+s.Substring(1);
}
#endregion
#region Camel命名
public string ToCamel(string s)
{
 return s.Substring(0,1).ToLower()+s.Substring(1);
}
#endregion

//得到外键信息
public Dictionary<ColumnSchema,TableKeySchema> FKDict
{
 get
 {
  if(fKDict==null)
   fKDict=getTableFKey();
  return fKDict;
 }
}

//得到类名
public string getClassName()
{
 return "frm"+this.ToPascal(this.SourceTable.Name);
}

//得到BindingSource控件名

public string getBindingSourceName()
{
 return "bds"+this.ToPascal(this.SourceTable.Name);
}

//得到BLL类全名

public string getBLLClassFullName()
{
 return "MasterSoft.BLL."+this.ToPascal(this.SourceTable.Name)+"BLL";
}

//得到BLL属性名

public string getBLLPropertyName()
{
 return this.ToCamel(this.SourceTable.Name)+"BLL";
}

#region 得到外键信息

public Dictionary<ColumnSchema,TableKeySchema> getTableFKey()
{
 Dictionary<ColumnSchema,TableKeySchema> fkDict=new Dictionary<ColumnSchema,TableKeySchema>();
 foreach(TableKeySchema key in this.SourceTable.ForeignKeys)
 {
  fkDict.Add(key.ForeignKeyMemberColumns[0],key);
 }
 return fkDict;
}
#endregion

//初使化ComboBox(我写的ComboboxProvider会对ComboBox进行初使化).

public string InitializeComboBox()
{
 string result="";
 foreach(ColumnSchema col in SourceTable.ForeignKeyColumns)
 {
  result+=string.Format("ComboboxProvider.{0}(this.{1});",this.ToPascal(FKDict[col].PrimaryKeyTable.Name),this.getControlName(col))+Enter;
 }
 return result;
}

//好像没用到....现在加注释才注意到.

public string FillComboBox()
{
 string result="";
 foreach(ColumnSchema col in SourceTable.Columns)
 {
  if(col.IsForeignKeyMember) 
   FillComboBox(col);
 }
 return result;
}

//好像有重复...
public string FillComboBox(ColumnSchema col)
{
 return string.Format("ComboboxProvider.{0}({1});",FKDict[col].PrimaryKeyTable.Name,this.getControlName(col))+Enter;
}

//绑定数据
public string BindingData()
{
 string result="";
 result+=Indent3+string.Format("DataSet ds = {0}.GetAllList();",this.getBLLPropertyName())+Enter;
 result+=Indent3+string.Format("{0}.DataSource = ds;",getBindingSourceName())+Enter;
 result+=Indent3+string.Format("{0}.DataMember = \"{1}\";",getBindingSourceName(),this.SourceTable.Name)+Enter;
 foreach(ColumnSchema col in SourceTable.Columns)
 {
  if(col.IsForeignKeyMember)
  {
   result+=Indent3+FillComboBox(col);
   result+=Indent3+string.Format("{0}.DataBindings.Add(\"SelectedValue\", {1}, \"{2}\");",this.getControlName(col),getBindingSourceName(),col.Name)+Enter;
  }
  else if(col.DataType== DbType.DateTime)
   result+=Indent3+string.Format("{0}.DataBindings.Add(\"Value\", {1}, \"{2}\");",this.getControlName(col),getBindingSourceName(),col.Name)+Enter;   
  else
   result+=Indent3+string.Format("{0}.DataBindings.Add(\"Text\", {1}, \"{2}\");",this.getControlName(col),getBindingSourceName(),col.Name)+Enter;   
 }
 if(this.HaveADatagridView)
 {
  result+=Indent3+string.Format("{0}.TableName = \"{1}\";",this.getDataGridViewControlName(),this.getSubTableName())+Enter;
  result+=Indent3+string.Format("{0}.DataMember = \"{1}\";",this.getDataGridViewControlName(),this.getFKName())+Enter;
  result+=Indent3+string.Format("{0}.DataSource = {1};",this.getDataGridViewControlName(),this.getBindingSourceName())+Enter;  
 }
 return result;
}

//得到DataSet中的外键名
public string getFKName()
{
 return "FK_"+this.SourceTable.Name+"_"+getSubTableName();
}

//得到子表名
public string getSubTableName()
{
 if(this.SourceTable.Name.EndsWith("Main"))
  return this.SourceTable.Name.Substring(0,SourceTable.Name.Length-4)+"Sub";
 else
  return this.SourceTable.Name+"Sub";
}

//得到Label控件名
public string getLabControlName(ColumnSchema col)
{
 return "lab"+this.ToPascal(col.Name);
}

//根据字段类型得到控件名

public string getControlName(ColumnSchema col)
{
 if(col.DataType==DbType.DateTime)
  return this.getDateTimePickerControlName(col);
 if(col.IsForeignKeyMember)
  return this.getComboBoxControlName(col);
 else
  return this.getTextBoxControlName(col);
}

//得到TextBox的控件名

public string getTextBoxControlName(ColumnSchema col)
{
 return "txt"+this.ToPascal(col.Name);
}

//得到ComboBox的控件名
public string getComboBoxControlName(ColumnSchema col)
{
 return "cob"+this.ToPascal(col.Name);
}

//得到DateTimePicker控件名
public string getDateTimePickerControlName(ColumnSchema col)
{
 return "dtp"+this.ToPascal(col.Name);
}

//得到DataGridView控件名
public string getDataGridViewControlName()
{
 return "dgv"+this.ToPascal(this.SourceTable.Name)+"Sub";
}

//声明Panel
public string DeclarePanelProperty()
{
 return Indent2+"private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; ";
}

//声明Lable

public string DeclareLableProperty()
{
 string result="";
 foreach(ColumnSchema col in SourceTable.Columns)
 {
  result+=Indent2+string.Format("private System.Windows.Forms.Label {0};",this.getLabControlName(col))+Enter;
 }
 return result;
}

//声明可编辑控件

public string DeclareControlProperty()
{
 string result="";
 foreach(ColumnSchema col in SourceTable.Columns)
 {
  if(col.IsForeignKeyMember)
  result+=Indent2+string.Format("private MComboBox {0};",this.getControlName(col))+Enter;
  else if(col.DataType==DbType.DateTime)
  result+=Indent2+string.Format("private MDateTimePicker {0};",this.getControlName(col))+Enter;
  else
  result+=Indent2+string.Format("private System.Windows.Forms.TextBox {0};",this.getControlName(col))+Enter;
 }
 if(this.HaveADatagridView)
  result+=Indent2+string.Format("private MDataGridView {0};",getDataGridViewControlName())+Enter;
 return result;
}

//实例化Panel

public string InstancePanel()
{
 return Indent3+"this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();";
}

//实例化Lable

public string InstanceLable()
{
 string result="";
 foreach(ColumnSchema col in SourceTable.Columns)
 {
  result+=Indent3+string.Format("this.{0} = new System.Windows.Forms.Label();",this.getLabControlName(col))+Enter;
 }
 return result;
}

//实例化可编辑控件

public string InstanceControl()
{
 string result="";
 foreach(ColumnSchema col in SourceTable.Columns)
 {
  if(col.IsForeignKeyMember)
   result+=Indent3+string.Format("this.{0} = new MasterSoft.WinUI.MComboBox();",this.getControlName(col))+Enter;
  else if(col.DataType==DbType.DateTime)
   result+=Indent3+string.Format("this.{0} = new MasterSoft.WinUI.MDateTimePicker();",this.getControlName(col))+Enter;
  else
   result+=Indent3+string.Format("this.{0} = new System.Windows.Forms.TextBox();",this.getControlName(col))+Enter;
 }
 if(this.HaveADatagridView)
  result+=Indent3+string.Format("this.{0} = new MasterSoft.WinUI.MDataGridView();",this.getDataGridViewControlName())+Enter;
 return result;
}

//根据数据源表的字段数及设定的Panel行数计算出Panel的列数

public int TabLayPanelColumnCount()
{
 int ColumnsCount=SourceTable.Columns.Count;
 int ControlCount=ColumnsCount*2;
 double tmp=ControlCount/TabLayPanelRowCount;
 int tmpInt=Convert.ToInt32(tmp);
 return (tmp>tmpInt?tmpInt+1:tmpInt);
}

//是否为偶数

public bool isEven(int num)
{
 double result=num/2.0;
 int resultInt= (int)result;
 return resultInt==result?true:false;
}

//初使化Panel

public string InitializeTableLayoutPanel()
{
 string result="";
 double rowCount=this.TabLayPanelRowCount;
 if(this.HaveADatagridView)
 {
  rowCount++;
 }
 int columnCount=this.TabLayPanelColumnCount();
 result+=Indent3+string.Format("//")+Enter;
 result+=Indent3+string.Format("// tableLayoutPanel1")+Enter;
 result+=Indent3+string.Format("//")+Enter;
 result+=Indent3+string.Format("this.tableLayoutPanel1.ColumnCount = {0};",columnCount)+Enter;
 for(int i=0;i<columnCount;i++)
 {
  if(isEven(i))
  result+=Indent3+string.Format("this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 98F));")+Enter;
  else
  result+=Indent3+string.Format("this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, {0}F));",10000/columnCount)+Enter;
 }
 for(int i=0;i<rowCount;i++)
 {
  for(int j=0;j<columnCount;j++)
  {
   int groupCount=(int)((i*columnCount+j)/2);
   if(groupCount<SourceTable.Columns.Count)
   {
    ColumnSchema col=SourceTable.Columns[groupCount];
    //result+=col.Name+Enter;
    if(isEven(i*columnCount+j))
     result+=Indent3+string.Format("this.tableLayoutPanel1.Controls.Add(this.{0}, {1}, {2});",this.getLabControlName(col),j,i)+Enter;
    else
     result+=Indent3+string.Format("this.tableLayoutPanel1.Controls.Add(this.{0}, {1}, {2});",this.getControlName(col),j,i)+Enter;
   }
  }
 }
 if(this.HaveADatagridView)
 {
  result+=Indent3+string.Format("this.tableLayoutPanel1.Controls.Add(this.{0}, {1}, {2});",this.getDataGridViewControlName(),0,this.TabLayPanelRowCount)+Enter;
 }
 result+=Indent3+string.Format("this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;")+Enter;
 result+=Indent3+string.Format("this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);")+Enter;
 result+=Indent3+string.Format("this.tableLayoutPanel1.Name = \"tableLayoutPanel1\";")+Enter;
 result+=Indent3+string.Format("this.tableLayoutPanel1.RowCount = {0};",rowCount)+Enter;
 for(int i=0;i<rowCount;i++)
 {
  result+=Indent3+string.Format("this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F));")+Enter;
 }
  if(this.HaveADatagridView)
 {
  result+=Indent3+string.Format("this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());")+Enter;
 }
 result+=Indent3+string.Format("this.tableLayoutPanel1.Size = new System.Drawing.Size(582, 156);")+Enter;
 result+=Indent3+string.Format("this.tableLayoutPanel1.TabIndex = 0;")+Enter;
 return result;
}

//初始化Lable

public string InitializeLable()
{
 string result="";
 foreach(ColumnSchema col in SourceTable.Columns)
 {
        result+=Indent3+string.Format("// ")+Enter;
        result+=Indent3+string.Format("// {0}",this.getLabControlName(col))+Enter;
        result+=Indent3+string.Format("// ")+Enter;
        result+=Indent3+string.Format("this.{0}.AutoSize = true;",this.getLabControlName(col))+Enter;
        result+=Indent3+string.Format("this.{0}.Location = new System.Drawing.Point(3, 25);",this.getLabControlName(col))+Enter;
        result+=Indent3+string.Format("this.{0}.Name = \"{0}\";",this.getLabControlName(col))+Enter;
        result+=Indent3+string.Format("this.{0}.Size = new System.Drawing.Size(71, 12);",this.getLabControlName(col))+Enter;
        result+=Indent3+string.Format("this.{0}.TabIndex = 0;",this.getLabControlName(col))+Enter;
        result+=Indent3+string.Format("this.{0}.Text = \"{1}\";",this.getLabControlName(col),col.Description)+Enter+Enter;
 } 
 return result;
}

//初始化可编辑控件

public string InitializeControl()
{
 string result="";
 int tabIndex=0;
 foreach(ColumnSchema col in SourceTable.Columns)
 {
  result+=Indent3+string.Format("// ")+Enter;
  result+=Indent3+string.Format("// {0}",this.getControlName(col))+Enter;
  result+=Indent3+string.Format("// ")+Enter;
  result+=Indent3+string.Format("this.{0}.Dock = System.Windows.Forms.DockStyle.Fill;",this.getControlName(col))+Enter;
  result+=Indent3+string.Format("this.{0}.Location = new System.Drawing.Point(83, 3);",this.getControlName(col))+Enter;
  result+=Indent3+string.Format("this.{0}.Name = \"{0}\";",this.getControlName(col))+Enter;
  result+=Indent3+string.Format("this.{0}.Size = new System.Drawing.Size(100, 21);",this.getControlName(col))+Enter;
  result+=Indent3+string.Format("this.{0}.TabIndex = {1};",this.getControlName(col),tabIndex)+Enter;  
  tabIndex++;
 }
 result+=InitializeDataGridView(tabIndex);
 return result;
}

//初始化DataGridView

public string InitializeDataGridView(int TabIndex)
{
 string result="";
 if(this.HaveADatagridView)
 {
  result+=Indent3+string.Format("//")+Enter;
  result+=Indent3+string.Format("// {0}",this.getDataGridViewControlName())+Enter;
  result+=Indent3+string.Format("//")+Enter;
  result+=Indent3+string.Format("this.{0}.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;",this.getDataGridViewControlName())+Enter;
  result+=Indent3+string.Format("this.tableLayoutPanel1.SetColumnSpan(this.{0}, {1});",this.getDataGridViewControlName(),this.TabLayPanelColumnCount())+Enter;
  result+=Indent3+string.Format("this.{0}.Dock = System.Windows.Forms.DockStyle.Fill;",this.getDataGridViewControlName())+Enter;
  result+=Indent3+string.Format("this.{0}.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter;",this.getDataGridViewControlName())+Enter;
  result+=Indent3+string.Format("this.{0}.InfoKeyColumnName = null;",this.getDataGridViewControlName())+Enter;
  result+=Indent3+string.Format("this.{0}.Location = new System.Drawing.Point(393, 78);",this.getDataGridViewControlName())+Enter;
  result+=Indent3+string.Format("this.{0}.Name = \"{0}\";",this.getDataGridViewControlName())+Enter;
  result+=Indent3+string.Format("this.{0}.OnclickModel = MasterSoft.WinUI.MDataGridView.ClickModel.OpenForm;",this.getDataGridViewControlName())+Enter;
  result+=Indent3+string.Format("this.{0}.RowTemplate.Height = 23;",this.getDataGridViewControlName())+Enter;
  result+=Indent3+string.Format("this.{0}.Size = new System.Drawing.Size(92, 150);",this.getDataGridViewControlName())+Enter;
  result+=Indent3+string.Format("this.{0}.TabIndex = {1};",this.getDataGridViewControlName(),TabIndex)+Enter;
  result+=Indent3+string.Format("this.{0}.TableName = null;",this.getDataGridViewControlName())+Enter;  
 }
 return result;
}

//引用需要的命名空间

public string UsingNameSpace()
{
 string result="";
 result+="using System;"+Enter;
 result+="using System.Collections.Generic;"+Enter;
 result+="using System.ComponentModel;"+Enter;
 result+="using System.Data;"+Enter;
 result+="using System.Drawing;"+Enter;
 result+="using System.Text;"+Enter;
 result+="using System.Windows.Forms; "+Enter;
 return result;
}

</script>

原文地址:https://www.cnblogs.com/tonyepaper/p/1280343.html