Created
June 26, 2024 10:30
-
-
Save bjoerntx/776178acccdd045da74cee6969fbe840 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void ConvertTextToTable(TXTextControl.TextControl textControl) | |
{ | |
if (textControl1.Selection.Length == 0) | |
{ | |
throw new Exception("No text selected."); | |
} | |
int[] storedTabPositions = textControl1.Selection.ParagraphFormat.TabPositions; | |
int startPosition = textControl1.Selection.Start; | |
int endPosition = startPosition + textControl1.Selection.Length; | |
var startLine = textControl1.Lines.GetItem(startPosition); | |
var endLine = textControl1.Lines.GetItem(endPosition - 1); | |
List<string> lineText = new List<string>(); | |
// Loop through all lines and add the text of each line to the list | |
for (int i = startLine.Number; i <= endLine.Number; i++) | |
{ | |
var line = textControl1.Lines[i]; | |
lineText.Add(line.Text); | |
} | |
// Calculate the number of rows and columns | |
int numRows = endLine.Number - startLine.Number + 1; | |
int numCols = lineText[0].Split('\t').Length; | |
textControl1.Selection.Text = string.Empty; | |
// Create a new table | |
var tableInserted = textControl1.Tables.Add(numRows, numCols); | |
// Set input position to the first cell | |
textControl1.Selection.Start -= 1; | |
// Loop through all rows and columns to populate the table | |
for (int i = 1; i <= numRows; i++) | |
{ | |
string[] splitText = lineText[i - 1].Split('\t'); | |
for (int j = 1; j <= numCols; j++) | |
{ | |
var tableCell = textControl1.Tables.GetItem().Cells[i, j]; | |
// Set the text of the cell, and remove the last CRLF | |
tableCell.Text = (splitText.Length >= j) ? splitText[j - 1].TrimEnd('\r', '\n') : string.Empty; | |
// Set the tab position if it's not the first column and the tab position exists | |
if (j > 1 && storedTabPositions.Length >= j - 1 && storedTabPositions[j - 1] != 0) | |
{ | |
tableCell.Position = storedTabPositions[j - 2]; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment