今天在工作做到處資料為Excel時,在用到DataGrid時,要求表頭為兩行 ,以前沒用過,把我難到了,又不想用用用戶端的Table,覺得可讀性太差,研究了一會,終於找到瞭解決方法,先發上來,由於時間關係,就不整理了。呵呵。
private void Datagrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
ListItemType itemtype=e.Item.ItemType; //獲得當前建立行的類別
int j=0;
if(itemtype==ListItemType.Header)//當執行到表頭是執行
{
DataGridItem trnew=new DataGridItem(0,0,ListItemType.Header);
for(int i=0;i<Datagrid1.Columns.Count;i++){
string strValue=Datagrid1.Columns[i].HeaderText;
if(strValue.Substring(0,2).Equals("A卷"))
{
string[] strArr=strValue.Split(',');
trnew.Cells.Add(new TableCell());
trnew.Cells[j].Text=strArr[1];
trnew.Cells[j].ColumnSpan=3;
trnew.Cells[j].Width=Unit.Pixel(180);
trnew.Cells[j].Height=Unit.Pixel(22);
e.Item.Cells[i].Text=strArr[0];
j=j+1;
}
else{
if(Datagrid1.Columns[i].HeaderText!="B卷"&&Datagrid1.Columns[i].HeaderText!="綜合")
{
trnew.Cells.Add(new TableCell());
trnew.Cells[j].Text=e.Item.Cells[i].Text;
trnew.Cells[j].RowSpan=2;
j=j+1;
}
}
}
j=0;
for(int i=0;i<Datagrid1.Columns.Count;i++)
{
if(Datagrid1.Columns[i].HeaderText!="B卷"&&Datagrid1.Columns[i].HeaderText!="綜合"&&Datagrid1.Columns[i].HeaderText.Substring(0,2)!="A卷")
{
e.Item.Cells.RemoveAt(j);
}
else{
j=j+1;
}
}
Datagrid1.Controls[0].Controls.AddAt(0,trnew);
}
}