前台
- HTML code
-
<form id="form1" runat="server"> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"> <EmptyDataTemplate> <asp:Label ID="Label1" runat="server" Text="没有数据!"></asp:Label> </EmptyDataTemplate> </asp:GridView> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> </form>
后台
- C# code
-
protected void Page_Init(object sender, EventArgs e) { Dictionary<string, string> columnsInfo = new Dictionary<string, string>(); columnsInfo.Add("Number", "编号"); columnsInfo.Add("Code", "编码"); columnsInfo.Add("Name", "名称"); foreach (string nameKey in columnsInfo.Keys) { TemplateField customTemp = new TemplateField(); customTemp.HeaderText = columnsInfo[nameKey]; GridViewCustomColumns gcc = new GridViewCustomColumns(nameKey); customTemp.ItemTemplate = gcc; GridView1.Columns.Add(customTemp); } } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { int id = 0; Dictionary<string, string> data = new Dictionary<string, string>(); data.Add("D0001", "公司1"); data.Add("D0002", "公司2"); data.Add("D0003", "公司3"); data.Add("D0004", "公司4"); DataTable Dt = new DataTable(); DataRow dr; Dt.Columns.Add("Number", typeof(string)); Dt.Columns.Add("Code", typeof(string)); Dt.Columns.Add("Name", typeof(string)); foreach (string skey in data.Keys) { dr = Dt.NewRow(); dr[0] = id.ToString(); dr[1] = skey; dr[2] = data[skey]; Dt.Rows.Add(dr); id++; } this.GridView1.DataSource = Dt; this.GridView1.DataBind(); } } protected void Button1_Click(object sender, EventArgs e) { }
类GridViewCustomColumns
- C# code
-
public class GridViewCustomColumns : ITemplate { string s_ColumnsName; public GridViewCustomColumns(string strName) { s_ColumnsName = strName; } void ITemplate.InstantiateIn(Control container) { Label lableName = new Label(); lableName.ID = s_ColumnsName; lableName.DataBinding += new EventHandler(lableName_DataBinding); container.Controls.Add(lableName); } void lableName_DataBinding(object sender, EventArgs e) { Label lable = (Label)sender; GridViewRow container = (GridViewRow)lable.NamingContainer; DataRowView dl = (DataRowView)container.DataItem; lable.Text = dl[lable.ID].ToString(); } }