图:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable oDataSource = CreateTable();
DataView oDV = oDataSource.DefaultView;
oDV.Sort = "StudentNo";
GvStudent.DataSource = oDV;
GvStudent.DataBind();
}
}
private DataTable CreateTable()
{
DataTable oDT = new DataTable();
oDT.Columns.Add("StudentNo");
oDT.Columns[0].DataType = typeof(System.Int32);
DataColumn oDC = new DataColumn("StudentName", typeof(System.String));
oDT.Columns.Add(oDC);
oDT.Columns.Add("Do1");
oDT.Columns.Add("Do2");
DataRow oDR = oDT.NewRow();
oDR[0] = 1001;
oDR["StudentName"] = "小张";
oDR["Do1"] = "学国学";
oDR["Do2"] = "学英语";
oDT.Rows.Add(oDR);
DataRow oDR1 = oDT.NewRow();
oDR1["StudentNo"] = 1004;
oDR1[1] = "小李";
oDR1[2] = "闲着";
oDR1[3] = "继续闲着";
oDT.Rows.Add(oDR1);
DataRow oDR2 = oDT.NewRow();
oDR2[0] = 1001;
oDR2["StudentName"] = "小张";
oDR2["Do1"] = "学英语";
oDR2["Do2"] = "学法语";
oDT.Rows.Add(oDR2);
return oDT;
}
int iPreStudentNo, iCurrentStudentNo;
int iPreRowNum;
int iMergeBegin = 2, iMergeEnd = 3;
protected void GvStudent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = e.Row.DataItem as DataRowView;
GridViewRow oRow=e.Row;
int.TryParse(drv["StudentNo"].ToString(), out iCurrentStudentNo);
if (oRow.RowIndex > 0)
{
//第二条记录才进行是否合并
if (iCurrentStudentNo != iPreStudentNo)
{
if (oRow.RowIndex - iPreRowNum > 1)
{
AddRowSpanForColumns(GvStudent.Rows[iPreRowNum], iMergeBegin, iMergeEnd, oRow.RowIndex - iPreRowNum);
}
iPreStudentNo = iCurrentStudentNo;
iPreRowNum = oRow.RowIndex;
}
else
{
RemoveColumnsFromRow(oRow, iMergeBegin, iMergeEnd);
}
}
else
{
//第一条记录
iPreStudentNo = iCurrentStudentNo;
iPreRowNum = oRow.RowIndex;
}
}
}
#region Combination Columns
private void AddRowSpanForColumns(GridViewRow oRow, int iIndexOfColumnBegin, int iIndexOfColumnEnd, int iRowspan)
{
//给上一个相同的加上Span
for (int i = 0; i < oRow.Cells.Count; i++)
{
if (i < iIndexOfColumnBegin || i > iIndexOfColumnEnd)
{
oRow.Cells[i].RowSpan = iRowspan;
}
}
}
/// <summary>
/// 移除列,进行合并
/// </summary>
/// <param name="oRow"></param>
/// <param name="iIndexOfColumnBegin"></param>
/// <param name="iIndexOfColumnEnd"></param>
private void RemoveColumnsFromRow(TableRow oRow, int iIndexOfColumnBegin, int iIndexOfColumnEnd)
{
for (int i = 0; i < oRow.Cells.Count; i++)
{
if (i < iIndexOfColumnBegin || i > iIndexOfColumnEnd)
{
oRow.Cells.RemoveAt(i);
i--;
iIndexOfColumnBegin--;
iIndexOfColumnEnd--;
}
}
}
#endregion