In ASP.NET, I have a FormView which is bound to an ObjectDataSource. The FormView has an ItemTemplate with a Delete button, and a Label. I'm handling the OnItemDeleted event of the FormView to detect if my business class throws an exception upon deletion. If an exception is detected, I change the text of the Label to whatever the exception message is.
Well, it's just not working.
I detect the Exception fine, but the Text of the Label never gets changed. When the page reloads, the default text stays. I have also tried to rebind the FormView with DataBind() after assigning the new Text, but it's not working either.
In a desperate attempt at tracking the problem, I've taken the Label out of the FormView and it's working fine.
What I am doing wrong?
ASPX page:
<asp:ObjectDataSource ID="MyObjectDataSource"
TypeName="MyScopeRepository"
SelectMethod="GetById"
DeleteMethod="Delete"
runat="server">
<SelectParameters>
<%-- The id param here is from a DropDownList, not included in the example for clarity. --%>
<asp:ControlParameter Name="id" Type="Int32" ControlID="MyDropDownList" PropertyName="SelectedValue" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="id" Type="Int32" />
</DeleteParameters>
</asp:ObjectDataSource>
<asp:FormView ID="MyFormView" DataSourceID="MyObjectDataSource"
RenderOuterTable="false"
DataKeyNames="Id"
OnItemDeleted="MyFormViewItemDeleted"
runat="server">
<ItemTemplate>
<asp:Button CssClass="Button Small" Text="Delete" CommandName="Delete" runat="server" /><br />
<asp:Label ID="ErrorLabel" Text="Default text" runat="server" />
</ItemTemplate>
</asp:FormView>
Code-behind:
protected void MyFormViewItemDeleted(object sender, FormViewDeletedEventArgs e)
{
if (e.Exception != null && e.Exception.InnerException is RepositoryException)
{
Label errorLabel = (Label)MyFormView.FindControl("ErrorLabel");
errorLabel.Text = e.Exception.InnerException.Message;
e.ExceptionHandled = true;
// I also tried this to no avail.
//MyFormView.DataBind();
}
}
Thanks a lot!
EDIT: I've checked all events fired by the FormView when clicking the Delete button and here is what I got:
- OnInit
- OnItemCreated
- OnLoad
- OnItemCommand
- OnItemDeleting
- OnItemDeleted
- OnItemCreated
- OnDataBound
- OnPreRender
- OnUnload
So we can see that OnItemCreated gets fired twice, and the second time it's fired is AFTER OnItemDeleted, which means that whatever change I make is overwritten, I suppose. Now how am I supposed to handle that?
Best Answer
Here is working solution (You may want to improve it):
codebehind: