Shaikh Aamir Shaikh Aamir - 2 months ago 16
ASP.NET (C#) Question

DataTable copying selected rows and columns to another DataTable by index

I have two DataTable's


  • ImportExcelDT

  • ExportExcelDT



Out of these two, one of the table contains some data, I am checking each row as validation and deleting the invalid columns from the table and adding it to the second table.

Here's the code, which I'm using

int Col = 0;
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(ImportExcelDT);

if (ImportExcelDT.Rows.Count > 0)
{
for (int i = 0; i < ImportExcelDT.Rows.Count; i++)
{

string EmpCod = ImportExcelDT.Rows[i]["Employee Code"].ToString();
bool isEmpCod = Regex.IsMatch(EmpCod, @"^[a-zA-Z0-9/-]+$");

//Here i am checking condition if its false
if (!isEmpCod)
{
count++;
//Now i want to copy and delete selected row in another data table
for (int j = 0; j < ImportExcelDT.Rows.Count; j++)
{
ImportExcelDT.Rows[j][i] = ExportExcelDT.Rows[j][Col];
ImportExcelDT.Rows[i].Delete();

}
}
else
{

}


I'm bit confused on which row & column should i select on
ImportExcelDT.Rows[j][i]
and
ExportExcelDT.Rows[j][Col];
while deleting and adding it.

Answer

try this one

if (ImportExcelDT.Rows.Count > 0)
{
    ExportExcelDT = ImportExcelDT.Clone();
    for (int i = 0; i < ImportExcelDT.Rows.Count; i++)
    {
        string EmpCod = ImportExcelDT.Rows[i]["Employee Code"].ToString();
        bool isEmpCod = Regex.IsMatch(EmpCod, @"^[a-zA-Z0-9/-]+$");
        //Here i am checking condition if its false
            if (!isEmpCod)
            {
                count++;
                //Now i want to copy and delete selected row in another data table 
                ExportExcelDT.ImportRow(ImportExcelDT.Rows[i]);
                ImportExcelDT.Rows[i].Delete();
            }
        else
        {

        }
    }
}