2017-07-29 56 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; } } –