Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge cells in a column using code behind?

C#, ASP.NET, VS08, using HTML table.

I want to merge cells - rowspan and colspan spans it but does not merge it.

For a clear picture,

  • drag a HTML table control on the design view
  • select the cells of a column
  • right click, modify, merge

I would like to do this programatically in C# coding on a button click.

like image 701
user287745 Avatar asked Aug 28 '10 13:08

user287745


People also ask

How do I merge cells in columns?

Merge cellsClick the first cell and press Shift while you click the last cell in the range you want to merge. Important: Make sure only one of the cells in the range has data. Click Home > Merge & Center.

How do you merge columns in HTML?

To merge table columns in HTML use the colspan attribute in <td> tag. With this, merge cells with each other. For example, if your table is having 4 rows and 4 columns, then with colspan attribute, you can easily merge 2 or even 3 of the table cells.

How do you merge cells vertically in HTML table?

To merge cells in HTML, use the colspan and rowspan attribute. The rowspan attribute is for the number of rows a cell should span, whereas the colspan attribute is for a number of columns a cell should span. Both the attribute will be inside the <td> tag.


1 Answers

It's just a little tedious to do this from code-behind, but the process is simple.

First off, I'm assuming your table and its elements are marked with the runat="server" attribute. This will give you access to the control's server-side API.

Say you want to merge two cells in the first row. The process involves setting the colspan of one cell, then removing the other(s).

myTable.Rows[0].Cells[i].ColSpan = 2;
myTable.Rows[0].Cells.RemoveAt(i + 1)

It is similar for rowspan.

myTable.Rows[0].Cells[i].RowSpan = 2;
myTable.Rows[1].Cells.RemoveAt(i)

Here is an example of a larger merge involving both rowspan and colspan:

myTable.Rows[0].Cells[i].ColSpan = 2;
myTable.Rows[0].Cells[i].RowSpan = 2;
myTable.Rows[0].Cells.RemoveAt(i + 1)
myTable.Rows[1].Cells.RemoveAt(i)
myTable.Rows[1].Cells.RemoveAt(i + 1)

Note that if your table already has row spans and cell spans that you will have more footwork to do to calculate which cells need removing.

Good luck!

like image 69
kbrimington Avatar answered Nov 05 '22 02:11

kbrimington