效果如上圖圖表的下半部分,這在中國的軟件項目中,也算一個比較常見的需求了。
實現代碼如下:
合併GridView單元格
public void MergeRows(ref GridView gv, int cellIndex)
{
int t = 0;
int count = 1;
string temp = gv.Rows[0].Cells[cellIndex].Text;
for (int i = 1; i < gv.Rows.Count; i++)
{
if (gv.Rows[i].Cells[cellIndex].Text == temp)
{
count++;
gv.Rows[t].Cells[cellIndex].RowSpan = count;
gv.Rows[i].Cells[cellIndex].Visible = false;
}
else
{
t = i;
count = 1;
temp = gv.Rows[i].Cells[cellIndex].Text;
}
}
}
public void MergeRows(ref GridView gv, int cellIndex)
{
int t = 0;
int count = 1;
string temp = gv.Rows[0].Cells[cellIndex].Text;
for (int i = 1; i < gv.Rows.Count; i++)
{
if (gv.Rows[i].Cells[cellIndex].Text == temp)
{
count++;
gv.Rows[t].Cells[cellIndex].RowSpan = count;
gv.Rows[i].Cells[cellIndex].Visible = false;
}
else
{
t = i;
count = 1;
temp = gv.Rows[i].Cells[cellIndex].Text;
}
}
}
在GridView的DataBound事件中調用上面的函數:
調用代碼
protected void gvTarget_DataBound(object sender, EventArgs e)
{
MergeRows(ref gvTarget,0);
MergeRows(ref gvTarget,1);
}
protected void gvTarget_DataBound(object sender, EventArgs e)
{
MergeRows(ref gvTarget,0);
MergeRows(ref gvTarget,1);
}