日期:2014-05-20 浏览次数:20806 次
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string[] cols = {"编号", "客户名称", "部门"};
object[][] testdata = {
new object[] {1, "A", "A1"},
new object[] {2, "A", "A2"},
new object[] {3, "A", "A3"},
new object[] {4, "B", "B1"},
new object[] {5, "C", "C1"},
new object[] {6, "C", "C2"},
new object[] {7, "D", "D1"}
};
dt.Columns.AddRange(cols.Select(c => new DataColumn(c)).ToArray());
foreach (var row in testdata)
dt.Rows.Add(row);
GridView gv = new GridView();
Page.Form.Controls.Add(gv);
gv.DataSource = dt;
gv.DataBind();
MergeColumnCells(gv, 1);
}
public void MergeColumnCells(GridView gv, int colIndex, Func<TableCell, TableCell, bool> mergable = null)
{
mergable = mergable ?? (Func<TableCell, TableCell, bool>)((c1, c2) => c1.Text == c2.Text);
var cells = gv.Rows.Cast<GridViewRow>().Select(r => r.Cells[colIndex]).Reverse().ToList();
int span = 1, i=0;
cells.ForEach(c =>
{
if (i < cells.Count-1 && mergable(c, cells[++i]))
{
c.Visible = false;
span++;
}
else
{
c.RowSpan = span;
c.Style.Value = "vertical-align: middle; text-align: center";
span = 1;
}
});
}