private void myGrid_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
//处理为0或0.00的项,是其为空(null)/
for(int i=0;i<=myGrid.Items.Count-1;i++)
{
for(int j=0;j<=myGrid.Columns.Count-1;j++)
{
if(myGrid.Items[i].Cells[j].Text=="0"||myGrid.Items[i].Cells[j].Text=="0.00")
{
myGrid.Items[i].Cells[j].Text=null;
}
}
}
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
for(int j=1;j<=myGrid.Columns.Count-1;j++)
{
e.Item.Cells[j].Attributes.Add("style","vnd.ms-excel.numberformat:@");
}
}
if(e.Item.ItemType==ListItemType.Header)
{
TableCellCollection tc=e.Item.Cells;
tc.Clear();
tc.Add(new TableHeaderCell());
tc[0].Text="xxxx";
tc[0].ColumnSpan=1;
tc[0].RowSpan = 2;
tc[0].Wrap=false;
tc.Add(new TableHeaderCell());
tc[1].Text="xxxx";
tc[1].ColumnSpan=2;
tc[1].RowSpan = 1;
tc[1].Wrap=false;
int minyear=int.Parse(DateTime.Parse(Page.Request.QueryString["dateFrom"]).Year.ToString());
for(int j=0;j<(this.myGrid.Columns.Count-3)/2-1;j++)//7-3=4/2=2-1=1
{
#region 前面列的处理
tc.Add(new TableHeaderCell());
tc[j+2].Text=minyear.ToString()+"年";
tc[j+2].ColumnSpan=2;
tc[j+2].RowSpan = 1;//2lie
tc[j+2].Wrap=false;
minyear=minyear+1;
#endregion
}
#region 关键处理
string yea=minyear.ToString()+"年";
tc.Add(new TableHeaderCell());
tc[(this.myGrid.Columns.Count-1)/2].ColumnSpan=2;
tc[(this.myGrid.Columns.Count-1)/2].RowSpan = 1;
tc[(this.myGrid.Columns.Count-1)/2].Wrap=false;
tc[(this.myGrid.Columns.Count-1)/2].Text="<font color='#ffffff'>"+yea+"</font></tr>";
tc[(this.myGrid.Columns.Count-1)/2].Text+="<tr><td align=center rowspan='1' colspan='1' bgcolor='#337FB2' nowrap><font color='#ffffff'>xxxx</font></td>";
for(int j=0;j<(this.myGrid.Columns.Count-3)/2;j++)
{
tc[(this.myGrid.Columns.Count-1)/2].Text+="<td align=center rowspan='1' colspan='1' valign=middle bgcolor='#337FB2' nowrap><font color='#ffffff'>xxxx</font></td>";
tc[(this.myGrid.Columns.Count-1)/2].Text+="<td align=center colspan='1' rowspan='1' valign=middle bgcolor='#337FB2' nowrap><font color='#ffffff'>xxxx</font></td>";
}
tc[(this.myGrid.Columns.Count-1)/2].Text+="<td align=center rowspan='1' colspan='1' bgcolor='#337FB2'nowrap><font color='#ffffff' nowrap>xxxx</font></td><tr>";
#endregion
}
}
本代码段根据你输入的开始和结束日期,重画动态生成绑定列的datagrid表头。关于如何动态生成绑定列在下篇中介绍。