ASP.NET ObjectDataSource UpdateMethod Exception Handling - asp.net

I have a GridView control on my page which is connected with ObjectDataSource where TypeName="BLL.MyLogic" DataObjectTypeName="BLL.MyObject" UpdateMethod="MyUpdateMethod".
The update in MyUpdateMethod is conditional which I am checking the conditions before _datacontext.submitchanges(). Depending on my check I throw exceptions like ("not unique") or ("no appropiate logic found") etc. I am catching these exceptions at page level via OnUpdated="MyDataUpdated" of my ObjectDataSource.
These operations just work fine. Problem is after the process is done and even in the case of "exception occured" the GridView gets reloaded and editindex = -1 (initiated). Even if I manually retrieve the editindex and make it editable the form data (data input by user) in the edittemplate gets wipped away. ViewState doesnt work here.
What is the work around to this situation ?
Thanks in advance.

Have you tried setting the GridViewUpdatedEventArgs.KeepInEditMode property to true in your RowUpdated event handler?

Related

ASP.Net Get Values ArgumentOutOfRangeException Thrown

I'm trying to loop through a gridview and save all the items in it at once. However I have a problem getting the values from the dropdownlist and textbox. I get this error each time:
ArgumentOutOfRangeException was caught. Specified argument was out of the range of valid values.
Here's the code I'm using:
foreach (GridViewRow gvr in gvInvalidOrgs.Rows)
{
try
{
org_code = Convert.ToInt32(gvr.Cells[0].Text);
division = ((DropDownList)gvr.Cells[1].Controls[0]).SelectedValue;
org_description = (((TextBox)gvr.Cells[2].Controls[0]).Text);
}
...
}
Both the textbox and the dropdownlists are dynamically created on rowbound if that matters.
TIA
Without knowing precisely which line the exception is thrown on, it's hard to diagnose with equal precision, but what's likely happening is that you're looking for a control in a cell that doesn't have any controls.
How could this come about? Well, since you are creating the controls in RowDataBound, if you don't bind your grid on every postback (and I'm not recommending that you do) your dynamically-added controls won't be recreated on postback. The posted data will include values for those controls, and ViewState will contain data for those controls, but if you don't recreate those controls on every postback, those controls won't exist when you attempt to access their values.
But you don't have to rebind to recreate the controls. As Mr. Schmelter says in his comment, if you move your creation of the controls from the RowDataBound to the RowCreated event handler, they will be created when the grid rows are re-created on postback.

ASP.NET - How to Get Result of a Data Binding in Code Before Binding?

Assuming I have access to the object that would be databound, and the settings for the databinding DataField, FormatString, etc...
How would I programattically get the resulting string value of a databinding without actually databinding to a control?
Context: This is in the overloaded InitializeCell event of a Telerik (Telerik.Web.UI) GridDropDownColumn that I am inheriting. I want to cache the resulting string value, but I need the value before the normal databinding event fires.
Just do a separate database query early in the page life cycle (pre-init) and cache the value manually...

Catch error in GridView automatic databinding

I have a gridview with a DataSourceID set, so the databinding happens automatically. The problem is that sometimes, the procedure defined in the SqlDataSource takes a very long time to finish, so the binding comes with a timeout expired error.
How can I catch this error without manually databinding the gridview and surrounding it with try/catch statements?
If an exception occurs when the SqlDataSource is executing, it fires its appropriate post-action event - Selected, in this case. You can optionally create an event handler for this event and in the event handler say that you've handled the exception.
This diagram shows how this interaction works with the ObjectDataSource (the concept is the same with the SqlDataSource control). When examining the diagram below, replace the words "ObjectDataSource" with "SqlDataSource" and "Underlying Object" with "Database" to have it be pertinent for the SqlDataSource.
As you can see, the Selecting event is raised before the data is sent off to the database and the Selected event is raised after the data comes back (or if there's an exception).
You can create a Selected event handler in your page and check to see if an exception occurred and decide whether you want to handle it yourself. Fredrik Normen has a good blog entry on this: Handle the data-source control exception by your own.
Additional reading material: Accessing and Updating Data in ASP.NET: Examining the Data Source Control's Events.
Happy Programming!
Why not fix the problem with the query timing out instead? Either optimise the DB (preferred) or set the connection/command timeout to be higher than the current value.
You can adjust the timeout as follows by hooking into the SqlDataSource Selecting event:
protected void ds_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
e.Command.CommandTimeout = 5000;
}
If you are using SQL Server you might want to look at tools like the index tuning wizard/tuning advisor, show query execution plan or SQL Server Profiler.
how about binding asynchronously? once completed, the callback function can call databind if no errors were returned.
EDIT: I guess that's manual...not what you wanted.
The only think you can do is handling the Page_Error Event
http://msdn.microsoft.com/en-us/library/ed577840.aspx

Dealing with Databinding Errors in ASP.net

This has been bugging me for a while but when I databind a control using with a Session variable as the parameter which has not been initialized there is an exception thrown which I can't seem to catch anywhere.
Ideally if the session varaible is not set I would just like to redirect but I can't seem to figure out where I need to check for this instance.
You must check the session object on page_init event.
Check it in your page load.
Sub Page_Load()
if Not Page.ispostback()
if session("Value") <>"" then
me.hiddenfield.value = Session("ValueName")
Else
Response.redirect("PAge.aspx")
End if
End if
End Sub
I tend to add some hidden fields as sessions eventually time out
then make the datasource use the hidden control for its reference

FormView_ItemUpdating in not updating

I am using a FormView to update an existing SQL Server record. The rows from the sqldatasource display fine in the FormView and I can edit them. When I click Update, I get the ItemUpdating event but not the ItemUpdated event and the revisions are not written to the database.
Can anyone help me in this please.
In your ItemUpdating event handler, make sure of the following things:
-If you are not using optimistic concurrency checking, remove any old values the FormView may be placing in the OldValues collection.
-Make sure that all of the parameters required by your stored procedure, query, or data source have values and are named correctly in either the Keys or NewValues collections (and make sure that no duplicates exist).
In some cases (usually when an ObjectDataSource is involved), I've had to override the values set by the FormView control, by doing something like this:
protected void myFormView_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
// remove the old values
e.Keys.Clear();
e.OldValues.Clear();
e.NewValues.Clear();
// set the parameter for the key
e.Keys.Add("#key", valueGoesHere);
// set other parameters
e.NewValues.Add("#param1", aValue);
e.NewValues.Add("#param2", anotherValue);
}
It's not pretty, but it give you absolute control over what gets passed to the DataSource. Generally you should not have to do this if the controls in your FormView are all bound using Bind() for two-way databinding (instead of Eval), but at the very least you could put a break point in ItemUpdating and open up the e.Keys, e.OldValues, and e.NewValues collections to see if the contents are what you expected.
A next step would be to launch SQL Server Profiler to run a trace and examine the actual query being performed.
If you take out the ItemUpdating event and the ItemUpdated event, does your SQL statement execute without errors?
If so, why don't you post some of the code you are using?
Can we see what the sqldatasource looks like? Did you remember to put all the parameters in the sqldatasource under the insert and update parameters list?
Oh also are you setting the cancel property at all in the itemupdating event?

Resources