87118

How to handle exceptions with a SqlDataSource

I have a SqlDataSource that is supplying data to my GridView. Thats all i am using on my form, thus i have NO code behind at all. But somewhere i need a TRY CATCH block just in case my connection get's lost. What code must i place where?

If i get a error i want my lblMessage Text to be "No connection".

<strong>Edit</strong>

My GridView in my Machine.aspx

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" Height="209px" PageSize="7" Width="331px" AllowSorting="True" DataSourceID="SqlDataSource1"> <Columns> <asp:BoundField DataField="Total" HeaderText="Total" ReadOnly="True" SortExpression="Total" DataFormatString="{0:R#,###,###}" > <HeaderStyle HorizontalAlign="Left" /> </asp:BoundField> <asp:BoundField DataField="b134_rmcid" HeaderText="Machine" ReadOnly="True" SortExpression="b134_rmcid" > <HeaderStyle HorizontalAlign="Left" /> </asp:BoundField> <asp:BoundField DataField="b134_recdate" DataFormatString="{0:d/MM/yyyy}" HeaderText="Date" ReadOnly="True" SortExpression="b134_recdate" > <HeaderStyle HorizontalAlign="Left" /> </asp:BoundField> </Columns> </asp:GridView>

My Connection right under my Gridview in my Machine.aspx

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ODBC_ConnectionString %>" ProviderName="<%$ ConnectionStrings:ODBC_ConnectionString.ProviderName %>" SelectCommand="SELECT SUM(b134_nettpay) AS Total, b134_rmcid, b134_recdate FROM B134HRE" onselected="SqlDataSource1_Selected"> </asp:SqlDataSource>

My Code in my Code Behind file in my Machine.aspx.cs

protected void Page_Load(object sender, EventArgs e) { lblError.Text = "hello there"; SqlDataSource1.Selected += new SqlDataSourceStatusEventHandler(SqlDataSource1_Selected); } protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e) { if (e.ExceptionHandled) { lblError.Text = "There is a problem"; } }

And still for some ready when i place a BreakPoint in my Selected Event it does not even get to it???

Why?

Answer1:

The SqlDataSource has an Selected event. Add a handler to this event like so, and handle any errors (show an informative message etc) in this handler.

void GridView1_Selected(object sender, SqlDataSourceStatusEventArgs e) { if (e.ExceptionHandled) { //Show error message } }

Sorry, but you're going to have to have some code in the code-behind!

<strong>Edit</strong>

Looking at your code, I don't think you're ever binding your GridView, so your SqlDataSource is never trying to select the data from your database.

In your Page_Load method, add the following code:

if (!IsPostBack) { GridView1.DataBind(); }

<strong>Further edit</strong>

Try changing "onselected" to "OnSelected" on your SqlDataSource and remove the line to bind your event handler in the code behind.

I'm stumped if that doesn't work as you've basically got the simplest-possible example.

<strong>Even further edit</strong>

Try this instead

void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e) { if (e.Exception != null) { //Show error message lblError.Text = "There is a problem"; //Set the exception handled property so it doesn't bubble-up e.ExceptionHandled = true; } }

Answer2:

you need to handle the error from code behind of your Gridview_ItemInserting or gridview_itemupdating so as to fire before your code are submitted to the sql control.

protected void GridView1_ItemInserting(object sender,DetailsViewInsertEventArgs e) { if (e.Exception != null) { Lblerror.text="error message" } }

do so also for updating

Answer3:

I believe you want to handle the Selected event of the SQLDataSource, and check the event argument for the exception.

Answer4:

Create an event handler for the Selected event of the SqlDataSource, test if an exception occurred, perform whatever error reporting you want, then indicate that you've now handled the error.

mSqlDataSource.Selected += new sqlDataSourceStatusEventHandler(mSqlDataSource_Selected); void mSqlDataSource_Selected(object sender, SqlDataSourceStatusEventArgs e) { if (e.Exception != null) { mErrorText.Text = e.Exception.Message; mErrorText.Visible = true; e.ExceptionHandled = true; } }

Answer5:

void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e) { if (e.Exception = null) { //bind data to gridview GridView1.DataBind(); } else { //Show error message lblError.Text = "There is a problem"; //Set the exception handled property so it doesn't bubble-up e.ExceptionHandled = true; } }

Recommend

  • uncommittable transaction is detected at the end of batch. the transaction is rolled back
  • Updating an Access Database via a DataGridView Using OLEDB in VB.NET
  • EntityDataSource query inner join
  • gridview rendered in div
  • Azure service bus paired namespace - simulate failover
  • Year, Month, and Day parameters describe an un-representable DateTime in Persian calender
  • jQuery - how to validate a date of birth using jQuery Validation plugin?
  • jQuery random blockquote
  • A simple datepicker in VueJS
  • String encoding problem on PdoStatement->bindParam()?
  • Binding a list with another list with WPF
  • Send Tor NEWNYM request using Java
  • How to parsing NSDate to RFC 822 always use in English?
  • ORA-12154: TNS:could not resolve the connect identifier specified
  • yii2 sorting in related model
  • Argument 5: cannot convert from 'System.Drawing.Image' to 'string' - calling cla
  • twisted.internet.error.ConnectError when run scrapy spider
  • openssl handshake failed
  • Connecting Google Cloud SQL with Wordpress on Google Compute Engine
  • stop execution in Custom validator if it false
  • Install phpMongo Drivers on windows
  • Changing media screen makes div overlay
  • Get localized short date pattern as String?
  • I am receiving HibernateException “No Hibernate Session bound to thread, and configuration does not
  • Cloud Code function running twice
  • what makes a request a new request in asp.net C#
  • MYSQ & MVC3 SQL connection error \\ ProviderManifestToken but I am using MySQL
  • Check for zero lines output from command over SSH
  • nonblocking BIO_do_connect blocked when there is no internet connected
  • Parse a date string in a specific locale (not timezone!)
  • Listbox within Listbox and scrolling trouble in Windows Phone 7 Silverlight
  • MailKit: The IMAP server replied to the 'EXAMINE' command with a 'BAD' response
  • Disable Enter in editText android
  • Illegal mix of collations for operation for date/time comparison
  • How to check if every primary key value is being referenced as foreign key in another table
  • Display Images one by one with next and previous functionality
  • Release, debug version and Authorization Google?
  • using conditional logic : check if record exists; if it does, update it, if not, create it
  • python regex in pyparsing
  • Hits per day in Google Big Query