Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Row from DataTable Depending on Condition

Tags:

c#

asp.net

I have a List that holds some IDs. I want to remove the rows from a DataTable where = ListLinkedIds

List<string> ListLinkedIds = new List<string>(); //This has values such as 6, 8, etc.
DataSet ds = new DataSet();
SqlDataAdapter da = null;
DataTable dt = new DataTable();



    da = new SqlDataAdapter("SELECT TicketID, DisplayNum, TranstypeDesc, SubQueueId, EstimatedTransTime,LinkedTicketId FROM vwQueueData WHERE (DATEADD(day, DATEDIFF(day, 0, Issued), 0) = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) AND QueueId = @QueueId AND SubQueueId = @SubQueueId   AND LinkedTicketId != @LinkedTicketId  AND Called IS NULL", cs);
   da.SelectCommand.Parameters.AddWithValue("@QueueId", Queue);
   da.SelectCommand.Parameters.AddWithValue("@SubQueueId", SubQueue);
   da.SelectCommand.Parameters.AddWithValue("@LinkedTicketId", ListLinkedIds[x]);
   da.Fill(ds);


//Removes from DataTable 
for (int x = 0; x < ListLinkedIds.Count(); x++)
{
   //Remove Row from DataTable Where ListLinkedIds[x]
}


gvMain.DataSource = ds;
gvMain.DataBind();

I tried dt.Rows.RemoveAt(remove) but that removes only the row number. I want to remove every row that is in the ListLinkedIds.

like image 381
Apollo Avatar asked Dec 12 '22 12:12

Apollo


2 Answers

Using LINQ you can create a new DataTable like:

DataTable newDataTable = dt.AsEnumerable()
                        .Where(r=> !ListLinkedIds.Contains(r.Field<string>("IDCOLUMN")))
                        .CopyToDataTable();
like image 80
Habib Avatar answered Dec 25 '22 05:12

Habib


You can select the rows and then remove the returned result.

public void test() {
        List<string> ListLinkedIds = new List<string>(); //This has values such as 6, 8, etc.
        DataSet ds = new DataSet();
        SqlDataAdapter da = null;
        DataTable dt = new DataTable();

        //Removes from DataTable 
        for (int x = 0; x < ListLinkedIds.Count(); x++)
        {
            DataRow[] matches = dt.Select("ID='" + ListLinkedIds[x] + "'");
            foreach (DataRow row in matches) {
                dt.Rows.Remove(row);
            }
        }


    }
like image 42
Ted Avatar answered Dec 25 '22 05:12

Ted