[轉帖]DataGrid顯示雙層表頭,即可實現合併單元格問題

weixin_33816946發表於2005-08-22
http://xml.sz.luohuedu.net/xml/ShowDetail.asp?id=B3F3462D-DC34-41CE-9FEE-6965B2A3D1AD
假設你的DataGrid有三列,現在想將前兩列作為"大類1",第三列作為"大類2",現在,你可以在ItemDataBound事件中加入下面的程式碼:
if (e.Item.ItemType == ListItemType.Header)
{
     e.Item.Cells[0].ColumnSpan = 2;
     e.Item.Cells[0].Text = "大類1</td><td>大類2</td></tr><tr><td>" + e.Item.Cells[0].Text;
}
用這個方法可以為任意新增新行。
 C#
if (e.Item.ItemType == ListItemType.Header)
                 {
                       DataGridItem dgi = new DataGridItem(0,-1,ListItemType.Header);
                       DataGridItem dgi1= new DataGridItem(0,-1,ListItemType.Header);
                       Table tb = new Table();
                       tb = (Table)DataGrid1.Controls[0];
                       tb.Rows.AddAt(0,dgi);
                       tb.Rows.AddAt(1,dgi1);
                       TableCell tc = new TableCell();
                       TableCell tc1 = new TableCell();
                       TableCell tc2 = new TableCell();
                       TableCell tc22 = new TableCell();
                       tc.Text = "ddd";
                       tc.ColumnSpan = 1;
                       dgi.Cells.Add(tc);
                       tc1.Text = "ddd2";
                       tc1.ColumnSpan = 1;
                       dgi.Cells.Add(tc1);
                       tc2.Text = "ddd";
                       tc2.ColumnSpan = 1;
                       dgi1.Cells.Add(tc2);
                       tc22.Text = "ddd2";
                       tc22.ColumnSpan = 1;
                       dgi1.Cells.Add(tc22);
                 
                 }


VB.NET顯示雙層表頭
    Dim dgi As DataGridItem
        Dim dgi1 As DataGridItem
        Dim tc As New TableCell()
        Dim tc1 As New TableCell()
        Dim tc2 As New TableCell()
        Dim tc22 As New TableCell()
        Dim tb As New Table()
        If (e.Item.ItemType = ListItemType.Header) Then

            dgi = New DataGridItem(0, -1, ListItemType.Header)
            dgi1 = New DataGridItem(0, -1, ListItemType.Header)
            tb = CType(DataGrid1.Controls(0), Table)
            tb.Rows.AddAt(0, dgi)
            tb.Rows.AddAt(1, dgi1)
            tc.Text = "ddd"
            tc.ColumnSpan = 1
            dgi.Cells.Add(tc)
            tc1.Text = "ddd2"
            tc1.ColumnSpan = 1
            dgi.Cells.Add(tc1)

            tc2.Text = "ddd"
            tc2.ColumnSpan = 1
            dgi1.Cells.Add(tc2)
            tc22.Text = "ddd2"
            tc22.ColumnSpan = 1
            dgi1.Cells.Add(tc22)
        End If

相關文章