将标题行添加到Gridview

时间:2013-04-02 13:32:13

标签: c# gridview datatable datasource dataview

我的gridview与此类似:

12- CategoryA - other columns
13- CategoryA - other columns
14- CategoryA - other columns
15- CategoryA - other columns

16- CategoryB - other columns
17- CategoryB - other columns
18- CategoryB - other columns

我想要的是那样的东西:

CategoryA (colspan 2) 
12 - other columns 
13 - other columns 
14 - other columns 
15 - other columns 
Category B (colspan 2) 
16 - other columns
17 - other columns 
18 - other columns

我可以通过修改绑定为数据源的数据表来实现吗?或者有更简单的方法吗?

2 个答案:

答案 0 :(得分:2)

我相信RowDataBound事件是你需要的。您可以跟踪以前显示的类别以及将显示的类别。

class MyClass
{
    private string CurrentCategory{ get; set; }

    // Load_Page with databinding the GridView{  }

    protected void mygridview_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if(e.Row.RowType == DataControlRowType.DataRow && 
          (e.Row.DataItem as DataRowView)["mycolumn"].ToString() != CurrentCategory))
        {
            GridViewRow tr = new GridViewRow(e.Row.RowIndex +1, e.Row.RowIndex + 1, 
                                   DataControlRowType.DataRow, e.Row.RowState);
            TableCell newTableCell = new TableCell();
            newTableCell.Text = (e.Row.DataItem as DataRowView)["mycolumn"].ToString();
            CurrentCategory = (e.Row.DataItem as DataRowView)["mycolumn"].ToString();
            tr.Cells.Add(newTableCell);

            ((Table)e.Row.Parent).Rows.Add(tr);
        }
    }
}

代码按原样提供,未经过测试。

答案 1 :(得分:0)

GridView控件不支持本机分组。