none
Print Filtered Rows Of DataTable RRS feed

  • Question

  • I have a datatable with a date column and I want to only print the rows where the column[1] = CurrentMonth.

    I have been using this to print all results, but how can I add in the condition of column[1] = currentmonth?

    foreach (DataRow dr in datatable1.Rows)
        foreach (var item in dr.ItemArray)
            Console.WriteLine(item);

    Tuesday, March 12, 2019 8:02 PM

Answers

  • Presumably, something like:

        foreach (DataRow dr in datatable1.Rows)
            if( dr["date"].Year == CurrentYear && dr["date"].Month == CurrentMonth )

    However, if this table came from a database, it would much smarter to do your selection in SQL instead, so you're only dealing with the rows you want, instead of the whole table.


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    • Marked as answer by IndigoMontoya Wednesday, March 13, 2019 8:30 PM
    Tuesday, March 12, 2019 9:03 PM

All replies

  • Presumably, something like:

        foreach (DataRow dr in datatable1.Rows)
            if( dr["date"].Year == CurrentYear && dr["date"].Month == CurrentMonth )

    However, if this table came from a database, it would much smarter to do your selection in SQL instead, so you're only dealing with the rows you want, instead of the whole table.


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    • Marked as answer by IndigoMontoya Wednesday, March 13, 2019 8:30 PM
    Tuesday, March 12, 2019 9:03 PM
  • Hi IndigoMontoya,

    Thank you for posting here.

    For your question, I simple example for your reference.

      // Here we create a DataTable with four columns.
                System.Data.DataTable table = new System.Data.DataTable();
                table.Columns.Add("Name", typeof(int));
                table.Columns.Add("Patient", typeof(string));
                table.Columns.Add("CurrentMonth", typeof(int));
    
                // Here we add five DataRows.
                table.Rows.Add(25, "David", 11);
                table.Rows.Add(50, "Sam", 5);
                table.Rows.Add(10, "Christoff", 4);
                table.Rows.Add(21, "Janet", 8);
                table.Rows.Add(100, "Melanie", 1);
    
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    Console.WriteLine(table.Rows[i]["CurrentMonth"]);
                }

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, March 13, 2019 5:48 AM
    Moderator