2017-07-29 57 views
0

兩行下面是我使用的代碼:此代碼的合併在GridView控件

protected void OnRowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    for (int rowIndex = gridView.Rows.Count - 2; 
            rowIndex >= 0; rowIndex--) 
    { 
     GridViewRow gvRow = gridView.Rows[rowIndex]; 
     GridViewRow gvPreviousRow = gridView.Rows[rowIndex + 1]; 
     for (int cellCount = 0; cellCount < 2; cellCount++) 
     { 
      if (gvRow.Cells[cellCount].Text.ToUpper().Trim() == 
            gvPreviousRow.Cells[cellCount].Text.ToUpper().Trim()) 
      { 
       if (gvPreviousRow.Cells[cellCount].RowSpan < 2) 
       { 
        gvRow.Cells[cellCount].RowSpan = 2; 
       } 
       else 
       { 
        gvRow.Cells[cellCount].RowSpan = 
         gvPreviousRow.Cells[cellCount].RowSpan + 1; 
       } 
       gvPreviousRow.Cells[cellCount].Visible = false; 
      } 
     } 
    } 
} 

輸出看起來像this image。 在這裏,紅圈表示輸出中的問題。當單元格到左列不同時,我不希望行合併。例如,如果銀行不同,控制辦公室不應該合併。

回答

0

請嘗試以下代碼。

<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" 
      RowStyle-BackColor="White" 
      runat="server" AutoGenerateColumns="false" OnRowDataBound = "OnRowDataBound"> 
      <Columns> 
       <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" /> 
       <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" /> 
      </Columns> 
     </asp:GridView> 


protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!this.IsPostBack) 
    { 
     DataTable dt = new DataTable(); 
     dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Country"), new DataColumn("Name") }); 
     dt.Rows.Add("USA", "John Hammond"); 
     dt.Rows.Add("USA", "Suzanne Mathews"); 
     dt.Rows.Add("Russia", "Robert Schidner"); 
     dt.Rows.Add("India", "Vijay Das"); 
     dt.Rows.Add("India", "Mudassar Khan"); 
     GridView1.DataSource = dt; 
     GridView1.DataBind(); 
    } 
} 

protected void OnRowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     if (e.Row.RowIndex > 0) 
     { 
      GridViewRow previousRow = GridView1.Rows[e.Row.RowIndex - 1]; 
      if (e.Row.Cells[0].Text == previousRow.Cells[0].Text) 
      { 
       if (previousRow.Cells[0].RowSpan == 0) 
       { 
        previousRow.Cells[0].RowSpan += 2; 
        e.Row.Cells[0].Visible = false; 
       } 
      } 
     } 
    } 
} 
+0

此代碼將只合並第一列行。我需要合併前2列行 –

+0

我上面的代碼工作正常只有問題是當第二列的行相同,但第一列的行不同 –

+0

檢查此代碼的列名更改爲(INT我= 0;我row.Cells.Count; i ++) if(row.Cells [i] .Text == previousRow.Cells [i] .Text) row.Cells [i] .RowSpan = previousRow.Cells [i ] .RowSpan <2? 2: previousRow.Cells [i] .RowSpan + 1; previousRow.Cells [i] .Visible = false; } } –