这是我正在使用的代码:
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 :(得分: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;
}
}
}
}
}