65.9K
CodeProject 正在变化。 阅读更多。
Home

合并DataGrid Header Columns

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.56/5 (10投票s)

2006年4月24日

viewsIcon

91971

本文描述了在运行时合并 DataGrid 标题列的简单技巧。

引言

本文描述了在运行时合并 DataGrid 标题列的简单技巧。

背景

我找到一个类似的解决方案:合并 DataGrid 标题,但我希望用 2-3 行代码实现。因此,我尝试使用 DataGrid 的成员来实现结果。

使用代码

DataGridItemCreated 事件中,捕获 DataGrid 的标题项。假设您要合并 n 列(标题行的单元格),则从标题项中删除 n-1 个单元格。然后,将剩余单元格的列跨度属性设置为 n。然后,根据您的要求在单元格中添加一个表格。下面的代码演示了合并两列,其结果如上图所示。

C#

private void  Sub Datagrid1_ItemCreated(object sender, 
        System.Web.UI.WebControls.DataGridItemEventArgs e )
{
    //If Header item
    
    If (e.Item.ItemType = = ListItemType.Header)
    {
        e.Item.Cells.RemoveAt(2);
        e.Item.Cells(1).ColumnSpan = 2;
        //Insert the table shown in the diagram 3
        // to the Text property of the Cell
        e.Item.Cells(1).Text = "<table style='FONT-WEIGHT: bold; WIDTH:" + 
              " 100%; COLOR: white; TEXT-ALIGN: center'><tr align" + 
              " =center><td colspan = 2 style='BORDER-BOTTOM:" + 
              " cccccc 1pt solid'>Name</td></tr>" + 
              "<tr align =center ><td style ='BORDER-RIGHT:" + 
              " cccccc 1pt solid'>F Name</td><td>L" + 
              " Name</td></tr></table>";
    }  
}

VB.NET

Private Sub Datagrid1_ItemCreated(ByVal sender As _
         Object, ByVal e System.Web.UI.WebControls.DataGridItemEventArgs)_
         Handles Datagrid1_ItemCreated 
    'If Header item
    
    If e.Item.ItemType = ListItemType.Header Then
       e.Item.Cells.RemoveAt(2)
       e.Item.Cells(1).ColumnSpan = 2
       'Insert the table shown in the diagram 3 to the Text property of the Cell
       e.Item.Cells(1).Text = "<table style='FONT-WEIGHT: bold;" & _ 
         " WIDTH: 100%; COLOR: white; TEXT-ALIGN: center'><tr" & _ 
         " align =center><td colspan = 2 style='BORDER-BOTTOM:" & _ 
         " cccccc 1pt solid'>Name</td></tr>" & _
         "<tr align =center ><td style ='BORDER-RIGHT:" & _ 
         " cccccc 1pt solid'>F Name</td><td>L" & _ 
         " Name</td></tr></table>"
    End If  
End Sub
合并 DataGrid 标题列 - CodeProject - 代码之家
© . All rights reserved.