合并gridview中具有相同值的asp.net中的单元格

时间:2012-07-24 15:52:06

标签: asp.net gridview

我在gridview

中有以下格式的数据
Region Branch
Gujrat Ahmedabad
Gujrat Surat
Gujrat Vadodara
Mumbai Dadar
Mumbai Andheri
Mumbai Borivali

但我想合并重复的值,如下所示

Region Branch
Gujrat Ahmedabad
       Surat
       Vadodara
Mumbai Dadar
       Andheri
       Borivali

我将数据从一个表格带到GridView。在GridView中,我有TemplateField标签是数据绑定。

1 个答案:

答案 0 :(得分:1)

您可以使用RowDataBound设置标签的文本,并检查它是否与上一个相同:

protected void Grid_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex > 0)
    {
        GridView grid = (GridView)sender;
        var rowView = (DataRowView)e.Row.DataItem;
        int lastRowIndex = e.Row.RowIndex - 1;
        var lastRowView = (DataRowView)grid.Rows[lastRowIndex].DataItem;
        // replace Region with the correct column name 
        String region = rowView.Row.Field<String>("Region");
        String lastRegion = lastRowView.Row.Field<String>("Region");
        // replace LblRegion with the correct ID of your Label
        Label label = (Label)e.Row.FindControl("LblRegion");
        label.Text = region != lastRegion ? region : "";
    }
}