DocX
DocX copied to clipboard
KeepWithNextParagraph() is not working with table rows
I tried to ensure that all child rows of a row stayed together on a single page and were not split between pages. I tried using KeepWithNextParagraph() but it didn't really work
class Program
{
static void Main(string[] args)
{
// Create a new document
using (DocX document = DocX.Create("Sample.docx"))
{
// Add a title and a space line after
document.InsertParagraph("Children's Schedule").FontSize(20).Bold().Alignment = Alignment.center;
document.InsertParagraph(); // Space line
document.InsertParagraph(); // Space line
document.InsertParagraph(); // Space line
// Assuming there are 10 children as an example
int numberOfChildren = 10;
int daysOfWeek = 5; // Monday to Friday
// Create the table
Table table = document.AddTable(numberOfChildren * 3 + 1, daysOfWeek + 2); // +2 for Childname and Type columns
// Setting the headers
SetTableHeaders(table);
// Filling in the data (this is dummy data, adjust as required)
for (int i = 0; i < numberOfChildren; i++)
{
SetChildRows(table, i, i);
}
// Add the table to the document
document.InsertTable(table);
// Save the document
document.Save();
}
Console.WriteLine("Document created!");
}
private static void SetTableHeaders(Table table)
{
table.Rows[0].Cells[0].Paragraphs[0].Append("Childname");
table.Rows[0].Cells[1].Paragraphs[0].Append("Type");
table.Rows[0].Cells[2].Paragraphs[0].Append("Monday");
table.Rows[0].Cells[3].Paragraphs[0].Append("Tuesday");
table.Rows[0].Cells[4].Paragraphs[0].Append("Wednesday");
table.Rows[0].Cells[5].Paragraphs[0].Append("Thursday");
table.Rows[0].Cells[6].Paragraphs[0].Append("Friday");
}
private static void SetChildRows(Table table, int childIndex, int actualChildIndex)
{
int baseRowIndex = childIndex * 3 + 1;
// Merge cells for child name across the 3 rows
table.MergeCellsInColumn(0, baseRowIndex, baseRowIndex + 2);
// Set child name in the merged cell
table.Rows[baseRowIndex].Cells[0].Paragraphs[0].Append($"Child {actualChildIndex + 1}");
string[] sessionTypes = { "AM", "PM", "PD" };
for (int j = 0; j < 3; j++)
{
table.Rows[baseRowIndex + j].Height = 30; // increase the row height
// Set session type for each row
table.Rows[baseRowIndex + j].Cells[1].Paragraphs[0].Append(sessionTypes[j]);
if (j < 2) // For AM and PM rows
{
table.Rows[baseRowIndex + j].Cells[1].Paragraphs[0].KeepWithNextParagraph();
}
}
}
}
Hi, Call the KeepWithNextParagraph() for each cell of the wanted row:
Thank you