gridview合併單元格ide
因爲項目要求,須要合併某些單元格,所以特地封裝了以下幫助類:spa
1 /// <summary> 2 /// 合併單元格 3 /// </summary> 4 public class MergeCellHelper 5 { 6 /// <summary> 7 /// 合併表頭 8 /// </summary> 9 /// <param name="row">當前行</param> 10 /// <param name="startColumn">開始列</param> 11 /// <param name="endColumn">結束列</param> 12 public static void MergeHeader(GridViewRow row, int startColumn, int endColumn) 13 { 14 for (int i = startColumn; i <= endColumn; i++) 15 { 16 if (i != startColumn) 17 { 18 row.Cells[i].Visible = false; 19 continue; 20 } 21 row.Cells[startColumn].ColumnSpan = endColumn - startColumn + 1; 22 } 23 } 24 25 /// <summary> 26 /// 合併指定列的行 27 /// </summary> 28 /// <param name="gv">gridview</param> 29 /// <param name="columns">指定的列:能夠多列</param> 30 public static void MergeRow(GridView gv, params int[] columns) 31 { 32 MergeRowByReferenceColumn(gv, 0, columns); 33 } 34 35 /// <summary> 36 /// 合併指定列的行(參考列必定要合理,慎用) 37 /// </summary> 38 /// <param name="gv">gridview</param> 39 /// /// <param name="referenceColumn">參照列</param> 40 /// <param name="columns">指定的列:能夠多列</param> 41 public static void MergeRowByReferenceColumn(GridView gv, int referenceColumn, params int[] columns) 42 { 43 for (int i = 0; i < columns.Length; i++) 44 { 45 var currentColumn = columns[i]; 46 int rowSpan = 1; 47 for (int j = 0; j < gv.Rows.Count; j++) 48 { 49 var currentRow = gv.Rows[j]; 50 if (j < gv.Rows.Count - 1) 51 { 52 var nextRow = gv.Rows[j + 1]; 53 if (currentRow.Cells[referenceColumn].Text == nextRow.Cells[referenceColumn].Text) 54 { 55 if (currentRow.Cells[currentColumn].Text == nextRow.Cells[currentColumn].Text) 56 { 57 rowSpan = rowSpan < 2 ? 2 : rowSpan + 1; 58 nextRow.Cells[currentColumn].Visible = false; 59 } 60 else 61 { 62 gv.Rows[j - rowSpan + 1].Cells[currentColumn].RowSpan = rowSpan; 63 rowSpan = 1; 64 } 65 } 66 else 67 { 68 gv.Rows[j - rowSpan + 1].Cells[currentColumn].RowSpan = rowSpan; 69 rowSpan = 1; 70 } 71 } 72 else 73 { 74 gv.Rows[j - rowSpan + 1].Cells[currentColumn].RowSpan = rowSpan; 75 rowSpan = 1; 76 } 77 } 78 } 79 } 80 81 82 }