简体   繁体   中英

copy datatable rows from one table to another

queryDataTable has the data within it and if the check is true that the row contrains that word it add that whole row to the extractedData .. but at the moment there is only two rows to be added to the extractedData datatable but when I inspect the data there is 22 row added to it is there any reason for this the code is below

DataTable dt = new DataTable();

for (int k = 0; k < queryDataTable.Rows.Count; k++)
{

    string row = "";
    string test = queryDataTable.Rows[k][0].ToString();
    bool check = queryDataTable.Rows[k][0].ToString().StartsWith(queryString);
    if (check)
    {
        int errorcheck = k;
        extractedData.ImportRow(queryDataTable.Rows[errorcheck]);

    }
}

how would i only add a row at a certain index in the first datatable

If you want to check the entire row this code can't work, with this instruction:

queryDataTable.Rows[k][0].ToString().StartsWith(queryString);

you check only the first column of the k-row. First, you can use this more compact code:

DataTable dt = new DataTable();
for (DataRow r in dt.Rows)
{
   if(r[0].startsWith(queryString))
   {
      extractedData.ImportRow(r);
   }
}

The if statament checks only the column 0 of each rows. If you specify to me the check that you want to do i can try to modify this code or create a linq query.

You can simply do this. (StartsWith checks if a string startswith a substring).

DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));

// Here we add five DataRows.
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);

var rows = table.AsEnumerable().Where(dr => dr.ItemArray.Contains("David"));

DataTable copyTable = new DataTable();
copyTable.Columns.Add("Dosage", typeof(int));
copyTable.Columns.Add("Drug", typeof(string));
copyTable.Columns.Add("Patient", typeof(string));
copyTable.Columns.Add("Date", typeof(DateTime));

foreach (var row in rows)
{
    copyTable.Rows.Add(row.ItemArray);
}

Sample data taken from https://www.dotnetperls.com/datatable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM