Search code examples
c#.netdatatableweb-controls

DataTable customization with records


I Have 1 Datatable having 10 rows and ListBox having 8 ListItems contains 6 records from the DataTable and 2 new records.

I want to update the DataTable in such a way that 6 records should be as it is and remove remaining 4 records from DataTable and add 2 newly added entries from ListBox in DataTable.

What I tried is I looped ListBox record from DataTable and created list of matched records.

string impactedTC;
List<int> index = new List<int>();
// This retruns my dataset having 10 records           
DataTable dttable = GetImpactedTestCaseDetailsToUpdateStatus().Tables[0];

for (int i = 0; i < ListBox1.Items.Count; i++)
{
    int count = 0;

    string dTestCase = ListBox1.Items[i].Text;
    foreach (DataRow dtRow in dttable.Rows)
    {
        impactedTC = dtRow["TestCaseName"].ToString();
        if (impactedTC == dTestCase)
        {
            index.Add(count);
        }
        count++;
    }
}

Solution

  • You can do that using Ling:

    To keep the 6 rows and remove the remaining 4 from the DataTable:

    //Assuming the names are DataTable1 and ListBox1.
    var rowsToRemove = from r in DataTable1.Rows.Cast<DataRow>()
            where listBox1.Items
            .Cast<ListItem>()
            .Aggregate(0, (n, li) => li.Text.ToLower() == r.Field<string>("TestCaseName").ToLower() ? n + 1 : n) == 0
            select r;
    

    To get the new items from the ListBox:

    var newItems = from li in listBox1.Items.Cast<ListItem>()
                    where DataTable1.Rows
                    .Cast<DataRow>()
                    .Aggregate(0, (n, r) => r.Field<string>("TestCaseName").ToLower() == li.Text.ToLower() ? n + 1 : n) == 0
                    select li;
    

    and finally update the DataTable:

    rowsToRemove.ToList().ForEach(r => DataTable1.Rows.Remove(r));
    newItems.ToList().ForEach(li => DataTable1.Rows.Add(li.Text)); //or maybe li.Value
    

    Important

    You might need to replace any li.Text with li.Value in the preceding code and that depends on how the ListItem objects are created. Please check this for more details.