动态创建gridview列
gdvSaleVoucher.Columns.Clear();
DataTable dt = new DataTable(); string strSql = @"select [level] from dbo.Film_FilmRelation group by [level] order by [level] desc "; using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["LocalConnectionString"].ConnectionString)) { SqlDataAdapter cmd = new SqlDataAdapter(strSql, conn); cmd.Fill(dt); } for (int i = 0; i < dt.Rows.Count; i++) { BoundField addbf = new BoundField();// addbf.DataField = "StickCarQutity" + (i + 1); addbf.DataFormatString = "{0:0.00#######}"; addbf.FooterStyle.CssClass = "text_right"; addbf.ItemStyle.CssClass = "text_right"; gdvSaleVoucher.Columns.Add(addbf);
} BoundField lastbf = new BoundField(); lastbf.DataField = "StickCarQutity"; lastbf.DataFormatString = "{0:0.00#######}"; lastbf.FooterStyle.CssClass = "text_right"; lastbf.ItemStyle.CssClass = "text_right"; gdvSaleVoucher.Columns.Add(lastbf);
//给该列命名
gdvSaleVoucher.HeaderText = "总数量";
gdvSaleVoucher.DataSource = dt;
gdvSaleVoucher.DataBind();
html
<asp:GridView ID="gdvSaleVoucher" runat="server" AutoGenerateColumns="False" ShowFooter="True" Width="400" OnDataBound="gdvSaleVoucher_DataBound"> <Columns> <asp:BoundField DataField="Customer" HeaderText="名称" SortExpression="Customer"> <ItemStyle HorizontalAlign="Center" /> <FooterStyle HorizontalAlign="Center" /> </asp:BoundField> </Columns> </asp:GridView>
databound给列命名
protected void gdvSaleVoucher_DataBound(object sender, EventArgs e) { if (gdvSaleVoucher.Rows.Count > 0) { DataTable dt = new DataTable(); string strSql = @"select [level] from dbo.Film_FilmRelation group by [level] order by [level] desc "; using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["LocalConnectionString"].ConnectionString)) { SqlDataAdapter cmd = new SqlDataAdapter(strSql, conn); cmd.Fill(dt); } for (int i = 0; i < dt.Rows.Count; i++) { gdvSaleVoucher.HeaderRow.Cells[i + 1].Text = dt.Rows[i]["level"].ToString();//给列命名 } gdvSaleVoucher.HeaderRow.Cells[dt.Rows.Count + 1].Text = "总数"; } }