Hello everybody,

I have a datagridview and one of the columns contains dates.

I want to loop through the data in the column using this for loop.

string StartDate="";
                string EndDate="";
                string date="";
                foreach (DataGridViewRow dgvr in dataGridViewTasksReport.Rows)
                {
                           date = dgvr.Cells["work_date_col"].Value.ToString();
                }

But what I want to do is get the smallest date and also get the largest date.

Any idea how to do this?

Thanks guys

Dani AI

Generated

Good call from and on the min/max pattern. Two gotchas to watch for in a DataGridView: 1) Cells["work_date_col"].Value might already be a DateTime (no parsing needed), and 2) the grid includes the placeholder new row, which you should skip. Also, string comparisons only work if the text is in a lexicographically sortable format like yyyy-MM-dd; safer is to compare DateTimes. Prefer DateTime.MinValue/DateTime.MaxValue over magic numbers.

Here is a defensive loop you can drop in. It ignores the time portion (use .Date) and guards against null/DBNull and culture parsing issues:

using System;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;

// ...

DateTime minDate = DateTime.MaxValue;
DateTime maxDate = DateTime.MinValue;

foreach (DataGridViewRow row in dataGridViewTasksReport.Rows)
{
    if (row.IsNewRow) continue;

    object val = row.Cells["work_date_col"].Value;
    if (val == null || val == DBNull.Value) continue;

    DateTime d;
    if (val is DateTime dt) d = dt.Date; // already a DateTime from the data source
    else if (!DateTime.TryParse(val.ToString(), CultureInfo.CurrentCulture, DateTimeStyles.None, out d)) continue;
    else d = d.Date;

    if (d < minDate) minDate = d;
    if (d > maxDate) maxDate = d;
}

// minDate/maxDate now hold the earliest and latest dates.

If your grid is data-bound, consider computing on the source instead of the UI for clarity and speed. Examples:

  • LINQ over grid rows: var dates = dataGridViewTasksReport.Rows.Cast<DataGridViewRow>().Where(r => !r.IsNewRow).Select(r => r.Cells["work_date_col"].Value).OfType<DateTime>().Select(d => d.Date); var min = dates.Min(); var max = dates.Max();
  • DataTable: table.Compute("MIN(work_date_col)", "work_date_col IS NOT NULL") and MAX(...).

This keeps ’s working approach, but makes it robust across nulls, mixed types, and time-of-day.

Recommended Answers

All 7 Replies

If your date strings are formatted correctly for string comparisons, you can just initialize them and do a comparison for min and max for each row in your loop (pseudocode):

if minDate = "" or minDate > date then
    minDate = date;
if maxDate = "" or maxDate < date then
    maxDate = date;
commented: He was execellent at helping me out and solving the probelm I had. Very reliable as well. +1

Can you give that to me in c#

Can you give that to me in c#

Give it a shot yourself in your loop. Then I will help you with questions. Be sure to post your new code.

I did make the code, but it didnt work well. here is what I have.

private DateTime StartDate;
        private DateTime EndDate;
//random date for iniitialaziton
                DateTime date = new DateTime(2000, 10, 10);
                foreach (DataGridViewRow dgvr in dataGridViewTasksReport.Rows)
                {
                    //date = dgvr.Cells["work_date_col"].Value.ToString();
                    StartDate = Convert.ToDateTime(dgvr.Cells["work_date_col"].Value);
                    EndDate = Convert.ToDateTime(dgvr.Cells["work_date_col"].Value);
                    if (StartDate > date)
                    {
                        StartDate = date;
                    }
                    if (EndDate < date)
                    {
                        EndDate = date;
                    }
                }
                MessageBox.Show(StartDate +" "+ EndDate,"getStartEndDate Error", MessageBoxButtons.OK, MessageBoxIcon.Information);

OK. Instead of initializing "date" outside the loop, restore it inside the loop, but use the Convert.ToDateTime. This is the value from each record we want to compare to to see if it is a min or max value.

Instead of initializing Start and EndDate inside the loop, move those outside the loop (where you have "date" currently): set your StartDate to a very high value; and your EndDate to a very low value.

This should fix it--let me know.

commented: Good explanation. +8

Set a mindate to 1.1.3000
Set a maxdate to 1.1.1900
Start a loop
Read a date
if date < mindate ---> set mindate = date
if date > maxdate ---> set maxdate = date

At the end of the loop you will have the max and mindate from your list. Succes!

Edit : DdoubleD, believe you posted a few seconds before me...

Brilliant! It worked perfectly!

Thanks so much DdoubleD, I really appreciate it!

Also, to anyone else who is dealing with a similar problem, here is the code that worked for me:

DateTime StartDate = new DateTime(9999, 10, 10);
                DateTime EndDate = new DateTime(1000, 10, 10);
                foreach (DataGridViewRow dgvr in dataGridViewTasksReport.Rows)
                {
                    DateTime date = Convert.ToDateTime(dgvr.Cells["work_date_col"].Value);
                    if (StartDate > date)
                    {
                        StartDate = date;
                    }
                    if (EndDate < date)
                    {
                        EndDate = date;
                    }
                }
                MessageBox.Show(StartDate +" "+ EndDate,"getStartEndDate Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.