Check dates before sql execution in asp.net

I have a data grid connected to a data source in a typical way (simplified for brevity):

<asp:SqlDataSource ID="ds" runat="server" ConnectionString="xxx"
     ProviderName="yyy" SelectCommand="SELECT "a from A where date > ?">
    <SelectParameters>
        <asp:ControlParameter ControlID="txtDateFrom" Name="fromDate" PropertyName="Value" Type="DateTime"/>
    </SelectParameters>

      

...

I also have a custom validator on txtDateFrom

<asp:CustomValidator ID="fromDateCorrectVal" runat="server" ControlToValidate="txtDateFrom"  ErrorMessage="From date is not valid" OnServerValidate="fromDateCorrectVal_ServerValidate" Display="None"/>

      

Where the code behind looks like this:

protected void fromDateCorrectVal_ServerValidate(object source, ServerValidateEventArgs args)
{
    DateTime parsedDate;
    if (!DateTime.TryParse(tryDate, out parsedDate))
    {
            args.IsValid = false;
            fromDateCorrectVal.ErrorMessage = "Invalid from date";
    }

}

      

But it doesn't work! If I put garbage in the date field, I get an ASP error - parsing invalid date tokens.

How can I stop trying to run SQL if validation is complete? (I suspect I need to check the isValid page at some point, but my attempts to try this in the datasource_Selecting event don't work)

Thanks in advance for your help

Ryan

+2


source to share


2 answers


You can handle this with SqlDataSource.Selecting and call Cancel.

By adding an event handler delegate to handle the Selecting event, you can perform any additional preprocessing required or cancel the database query entirely. Because the SqlDataSourceSelectingEventArgs class is derived from the SqlDataSourceCommandEventArgs class, you can cancel the pending SqlDataSource database Query for the Cancel property to true. You can examine and the CommandText, parameter set, and other properties of the database query before running the query by accessing the DbCommand object exposed using the Command property. You can also examine the DataSourceSelectArguments Object that is passed to the Select method to access the Arguments property.



http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasourceselectingeventargs.aspx

+2


source


Another way to achieve this is to use CompareValidator:

<asp:CompareValidator id="dateValidator" runat="server" Type="Date" Operator="DataTypeCheck" ControlToValidate="txtDateFrom" ErrorMessage="Error!" />

      



This validator has a built-in date validation function and does not allow the page to continue processing until all validations have passed.

0


source







All Articles