Add rows to existing table in word file (doc file) using DocX dll

Oct 11, 2016 at 4:56 PM
Edited Oct 12, 2016 at 4:38 PM
i have a problam with adding rows to my existing table, in my application im manipulating word file. in my template (word file) there is allready a table with 8 rows not including the header(you can see in the picture), when building a new word file in my app,sometimes i want to add more rows to the table because maybe i have more data to insert in(data from dataGridView). like in the code below, im adding rows according to how much rows i have from my datagridview,asking this:
using (DocX document = DocX.Load(filename))
{
    int k = 0;

    Table t = document.Tables[0];

    // Specify some properties for this Table.
    t.Alignment = Alignment.right;

    if (howManyRows > t.RowCount)
    {
        int x = howManyRows - t.RowCount;
        for (int i = 0; i < x; i++)
        {
            Row row = t.InsertRow();             
        }
    }  
and i tried also just: t.InsertRow();

and then im populating my table in the word file from my dataGridView and then i get an unhandled exception-index was out of range, which makes no sense,because if im not adding rows, just populating the table with the same rows number with the same code, i get no exception and the table is working fine, this is the code that i did to populate from list of string from dataGridView:
for (int i = 1; i <=howManyRows; i++)
{
    for (int j = 4; j >= 0; j--)
    {
        t.Rows[i].Cells[j].Paragraphs.First().Append(dataFromDataGrid[k]).FontSize(11).Font(new FontFamily("Arial"));
        k++;
    }
}
document.Save();
i think im not adding rows as needs to be done because if im running in my loop until :
 for (int i = 1; i <howManyRows; i++)
not like :
for (int i = 1; i <=howManyRows; i++)
as i did below, im getting this table : as the picture shows,there are no cells and borders in the rows maybe this is the problam i dont know.

Image
Nov 11, 2016 at 11:09 AM
just remove all rows from the table except the header then try:

using (DocX document = DocX.Load(filename))
{
int k = 0;

Table t = document.Tables[0];

// Specify some properties for this Table.
t.Alignment = Alignment.right;

 for (int i = 1; i <=howManyRows; i++)
 {
       t.InsertRow();
       for (int j = 4; j >= 0; j--)
      {
             t.Rows[t.Rows.Count - 1].Cells[j].Paragraphs.First().Append(dataFromDataGrid[k]).FontSize(11).Font(new FontFamily("Arial"));
             k++;
      }
}
document.Save();
}
Nov 15, 2016 at 10:59 AM
delete the rows of the existing table ?
how to do it properly?

and when ill delete it , how i will know the position of the header to start adding rows like you said ?