您好,登錄后才能下訂單哦!
今天修改舊的項目,發現之前用到的gridview合并單元格代碼不適用于模板列。做了修改之后記錄下來。
兩種方法,第一種適用于所有情況,第二種適用于合并依據列非模板列。
兩種方法如下:
方法一:
/// <summary>
/// 合并GridView中某列相同信息的行(單元格) 包含模板列 根據ID=rowspanid 的hiddenfield控件的值來合并。需要合并的 單元格需加上這個控件。根據控件值合并。可以將控件放在某一列,也可以放在每一列。取值的時候分開就行。此方法適合任意列,特別是模板列 無法取cell.text的時候
/// </summary>
/// <param name="GridView1">GridView</param>
/// <param name="cellNums">合并第幾列</param>
/// <param name="rowspanid">合并依據控件ID,這里用的hiddenfield控件。只需將ID=rowspanid的hiddenfield控件放在單元格里即可</param>
public static void GroupRows(GridView GridView1, int[] cellNums, string rowspanid = "hfrowspan")
{
foreach (int cellNum in cellNums)
{
int i = 0, rowSpanNum = 1;
while (i < GridView1.Rows.Count - 1)
{
GridViewRow gvr = GridView1.Rows[i];
for (++i; i < GridView1.Rows.Count; i++)
{
GridViewRow gvrNext = GridView1.Rows[i];
if (((HiddenField)gvr.Cells[cellNum].FindControl(rowspanid)).Value == ((HiddenField)gvrNext.Cells[cellNum].FindControl(rowspanid)).Value)
{
gvrNext.Cells[cellNum].Visible = false;
rowSpanNum++;
}
else
{
gvr.Cells[cellNum].RowSpan = rowSpanNum;
rowSpanNum = 1;
break;
}
if (i == GridView1.Rows.Count - 1)
{
gvr.Cells[cellNum].RowSpan = rowSpanNum;
}
}
}
}
}
方法二:
/// <summary>
/// 根據某一列合并其他列。依據的列不能是模板列,否則請用上一個方法↑。
/// </summary>
/// <param name="GridView1">GridView</param>
/// <param name="cellNums">合并第幾列,數組</param>
/// <param name="byCellNum">依據第幾列</param>
public static void GroupRowsByOne(GridView GridView1, int[] cellNums, int byCellNum)
{
foreach (int cellNum in cellNums)
{
int i = 0, rowSpanNum = 1;
while (i < GridView1.Rows.Count - 1)
{
GridViewRow gvr = GridView1.Rows[i];
for (++i; i < GridView1.Rows.Count; i++)
{
GridViewRow gvrNext = GridView1.Rows[i];
//if (((HiddenField)gvr.Cells[cellNum].FindControl(rowspanid)).Value == ((HiddenField)gvrNext.Cells[cellNum].FindControl(rowspanid)).Value)
if(gvr.Cells[byCellNum].Text== gvrNext.Cells[byCellNum].Text)
{
gvrNext.Cells[cellNum].Visible = false;
rowSpanNum++;
}
else
{
gvr.Cells[cellNum].RowSpan = rowSpanNum;
rowSpanNum = 1;
break;
}
if (i == GridView1.Rows.Count - 1)
{
gvr.Cells[cellNum].RowSpan = rowSpanNum;
}
}
}
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。