Insert Visible ASP:GridViewRows Into DataTable

I am hiding asp:gridviewrows based off a checkbox in the grid, and if they are hidden I do not want to insert them into the Data Table. I am trying the below syntax, but I am getting a Debug Error of

Additional information: A column named 'column0' already belongs to this DataTable.

This line of code throws the error datatablefirst.Columns.Add....

How should I alter my syntax to remove this issue?

foreach (GridViewRow row in gridviewmain.Rows)
{
    CheckBox chk = (CheckBox)row.Cells[0].FindControl("checkboxforcode");
    if (chk.Checked == true)
    {
        for (int i = 0; i < gridviewmain.Columns.Count; i++)
        {
            datatablefirst.Columns.Add("column" + i.ToString());
        }
        DataRow dr = datatablefirst.NewRow();
        for (int j = 0; j < gridviewmain.Columns.Count; j++)
        {
            dr["column" + j.ToString()] = row.Cells[j].Text;
        }
        datatablefirst.Rows.Add(dr);
    }
}

1 answer

  • answered 2018-01-11 20:29 Ctznkane525

    You only want to add the columns if they don't exist. That's not done per row.

    bool columnsAdded = false;
    foreach (GridViewRow row in gridviewmain.Rows)
    {
        CheckBox chk = (CheckBox)row.Cells[0].FindControl("checkboxforcode");
        if (chk.Checked == true)
        {
            if (!columnsAdded )
            {
                for (int i = 0; i < gridviewmain.Columns.Count; i++)
                {
                    datatablefirst.Columns.Add("column" + i.ToString());
                }
                columnsAdded = true;
            }
            DataRow dr = datatablefirst.NewRow();
            for (int j = 0; j < gridviewmain.Columns.Count; j++)
            {
                dr["column" + j.ToString()] = row.Cells[j].Text;
            }
            datatablefirst.Rows.Add(dr);
        }
    }