I have a basic app which contains a gridview with a sqldatasource. The datasource includes two date parameters. The params are linked to two textboxes which are prepopulated but can be modified by the user for their desired date range. I have two validation controls on each textbox. A requiredfieldvalidator and a comparefieldvalidator. The latter being a check for a valid date format.
When I (intentionally) break one of the dates, say, by adding a letter e.g 19/03/2014a (I'm in the U.K, date format is dd/mm/yy) the validation kicks in perfectly and it returns a message to say the date is invalid.
The issue:
Now at this point if I immediately select a row on the gridview, the app derails and I get an error: "Conversion failed when converting datetime from character string" This is expected given that I am using the dates in the textboxes as parameters for my gridview datasource and one of them now contains an invalid date. In an attempt to prevent the SelectedIndexChanged firing at all I have tried to handle the SelectedIndexChanging event for the gridview and cancel the row select. Here is the code for that:
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
Page.Validate();
if (!Page.IsValid)
{
e.Cancel = true;
return;
}
}
This codes "works" in that it prevents the SelectedIndexChanged event and also the gridview databind, BUT, I still get the same error: "Conversion failed when converting datetime from character string".
Can someone assist me with this please?
Help much appreciated as ever!
kind regards
Paul.
EDIT: Well I tried the suggestion of a regular expression. I removed other validators(both required and compare) The same error arises. No change.
What I don't understand is that when I cancel the the gridview selected index change event in "GridView1_SelectedIndexChanging" and the "GridView1_SelectedIndexChanged" does not fire, I would expect then that the page would be returned unchanged. But it totally derails and brings up the error. Why?! I'm cancelling the action!
When I step through the code with the invalid date entered, I can see that the gridview is not being databound there. Is it possibly attempting to DataBind() anyway?
Help appreciated greatly!
regards Paul
EDIT: I finally solved this myself. I disabled automatic databinding and called DataBind() myself at the appropriate times. Another measure I thought of was to add validation login in the T-SQL so that invalid dates did not result in querying the db. There is likely to be a better solution but I couldn't find it and no one suggested it.