I am wondering if anyone knows if it is possible to verify the values of Insert or Update parameters on a SqlDataSource before it reaches the database.
My problem is that I have a DateTime field that a user can enter information into. If they enter say, "hello world"; there will be an exception thrown since that is obviously a wrong value. I am wondering if it's possible to catch that, stop the insert, and elegantly display an error message.
Right now, I am using this in conjunction with a FormDetail. I've tried catching this error in the OnInserting command, with little success. Using e.Cancel = true causes the form to revert to its previous mode, losing all user data. Below is my current code.
Thanks for any advice,
Craig
(Presentation)
Fields are also bound using Text='<%# Bind() %>' syntax.
<asp:SqlDataSource ID="AnnounceDetailSource" Runat="server" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="Announcement_Get"
InsertCommand="Announcement_Insert"
OnInserting="Announce_Inserting">
<SelectParameters>
<asp:ControlParameter Name="id" Type="Int32" ControlID="AnnounceView" PropertyName="SelectedValue"></asp:ControlParameter>
</SelectParameters>
<InsertParameters>
<asp:Parameter name="title" />
<asp:Parameter Name="topic" />
<asp:Parameter Name="content" />
<asp:Parameter name="expire_date" />
<asp:SessionParameter Name="author" Type="String" SessionField="LoginName" />
</InsertParameters>
</asp:SqlDataSource
(Code-Behind)
void Announce_Inserting(object sender, SqlDataSourceCommandEventArgs e)
{
try
{
Convert.ToDateTime(e.Command.Parameters["expire_date"]);
}
catch
{
e.Command.Parameters["expire_date"] = DateTime.Now;
}
}You can instead add the CustomValidation control to your form.
Thanks for the tip,
I thought I tried that at one point; but I kept getting "control does not exist".
One problem I did notice is that the validator controls are still validating (in this case, a regular expression validator), even if the user hits the cancel button. Do you know of any way to make them only sensitive to the update or insert command?
Thanks,
Craig
When you want to get a parameter from the DbCommand object you need to add the "@." char before the name of the parameter:
e.Command.Parameters["@.expire_date"]
To disable the validation, add set the CausesValidation attribute of your cancel button to false.
No comments:
Post a Comment