blah blah blah is here! blah blah » Close

up0down
link

How can i parse the below datetime as exact?

DateTime dt = DateTime.Parse(row.Cells[2].Value.ToString());


when the above code is executed i get error: 'String was not recognized as a valid DateTime.'

the format of the date in that column is as follows: dd/MM/yyyy mm:HH:ss

last answered one year ago

3 answers

link

It's probably because you're using a 'foreach' loop but making changes to the collection each time a Row is deleted which changes the indexing of the remaining rows. In effect, the next row after the one deleted will be skipped even though it may need deleting itself.

When you're doing multiple deletions, the safest thing to do is to use an ordinary 'for' loop but iterate through the collection backwards so that deletions don't affect the indexing of the remaining elements.

I'd therefore try it like this:

string format = "dd/MM/yyyy HH:mm:ss";
for(int i = calDataGridView.Rows.Count - 2; i >= 0; i--) // ignores 'new' row
{
DataGridViewRow row = calDataGridView.Rows[i];
DateTime dt = DateTime.ParseExact(row.Cells[2].Value.ToString(), format, null);
if (dt < DateTime.Today) // gives 12:00 am today
{
calDataGridView.Rows.RemoveAt(i);
}
}

Thank you very much, i have applied that format and it works great. and thanks for the advice.

up1down
link

I'd try:

string format = "dd/MM/yyyy mm:HH:ss";
DateTime dt = DateTime.ParseExact(row.Cells[2].Value.ToString(), format, null);

Incidentally, are you sure that the minutes precede the hours which is an unusual format?

up1down
link

Ooops yes you was right vulpes, typo there ;-)

Your code does build fine with no errors, i'm using it as below, my plan is to remove the row that contains a date older than todays date, the below kind of works but still shows some older dates, can you see what i'm doing wrong?

foreach (DataGridViewRow row in calDataGridView.Rows)
{
if (row.IsNewRow) break;
string format = "dd/MM/yyyy HH:mm:ss";
DateTime dt = DateTime.ParseExact(row.Cells[2].Value.ToString(), format, null);
if (dt < DateTime.Today.AddDays(0))
{
calDataGridView.Rows.Remove(row);
}
}

Feedback