Skip to content

Instantly share code, notes, and snippets.

@bjoerntx
Last active October 20, 2021 19:55
Show Gist options
  • Save bjoerntx/553f1d5021a574dafb50a537187c3aa9 to your computer and use it in GitHub Desktop.
Save bjoerntx/553f1d5021a574dafb50a537187c3aa9 to your computer and use it in GitHub Desktop.
private bool MergeSimilarCells(TXTextControl.Table table, bool firstIteration = true) {
// loop through all column separately
foreach (TXTextControl.TableColumn col in table.Columns) {
bool bMergeFlag = false;
int iFirstRow = 0;
string sCommonCellText = "";
// row by row
for (int row = 1; row <= table.Rows.Count; row++) {
// only cells that are not merged
if (table.Cells[row, col.Column].Length != -1) {
// if table cell contains text from previous cell
// set "bMergeFlag" to true and flag row number
if (table.Cells[row, col.Column].Text == sCommonCellText) {
if (bMergeFlag == false) iFirstRow = row;
bMergeFlag = true;
}
// if text is different and "bMergeFlag" is true, merge cells
else if (bMergeFlag == true) {
MergeCells(table, iFirstRow - 1, col.Column, row - 1, col.Column, sCommonCellText);
bMergeFlag = false;
}
// if flag "bMergeFlag" is true and it is the last row, merge cells
if (bMergeFlag == true &&
row == table.Rows.Count &&
table.Cells[row, col.Column].Text == sCommonCellText) {
MergeCells(table, iFirstRow - 1, col.Column, row, col.Column, sCommonCellText);
}
// remember current cell text
if (row < table.Rows.Count)
sCommonCellText = table.Cells[row, col.Column].Text;
}
}
}
// two iterations required as rows are potentially merged
if (firstIteration == true)
MergeSimilarCells(table, false);
return false;
}
// this method simply merges given cells and sets the common cell text
private void MergeCells(
TXTextControl.Table table,
int startRow,
int startColumn,
int stopRow,
int stopColumn,
string newText) {
table.Select(startRow, startColumn, stopRow, stopColumn);
table.MergeCells();
table.Cells[startRow, startColumn].Text = newText;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment