asp.net try, catch, finally, Exception example: how to handle error
ErrorHandlingExample.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Configuration" %>
<!DOCTYPE html>
<script runat="server">
protected void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
string selectSql = "SELECT ProductID, ProductName, UnitPrice FROM Products ";
selectSql += "Where CategoryID=" + DropDownList1.SelectedValue;
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
SqlCommand myCommand = new SqlCommand(selectSql,myConnection);
SqlDataReader myReader;
try
{
myConnection.Open();
myReader = myCommand.ExecuteReader();
GridView1.DataSource = myReader;
GridView1.DataBind();
}
catch (Exception err)
{
Label1.Text = "Error: " + err.ToString();
}
finally
{
myConnection.Close();
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net try, catch, finally, Exception example: how to handle error</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Red">Example: Error Handling</h2>
<asp:DropDownList
ID="DropDownList1"
runat="server"
DataSourceID="SqlDataSource1"
DataTextField="CategoryName"
DataValueField="CategoryID"
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
BackColor="CornflowerBlue"
ForeColor="AliceBlue"
>
</asp:DropDownList>
<asp:SqlDataSource
ID="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT CategoryID, CategoryName FROM Categories"
>
</asp:SqlDataSource>
<br /><br />
<asp:Label ID="Label1" runat="server" ForeColor="Red" Font-Italic="true">
</asp:Label>
<asp:GridView
ID="GridView1"
runat="server"
BackColor="CornflowerBlue"
ForeColor="AliceBlue"
BorderColor="LightBlue"
Font-Italic="true"
GridLines="Horizontal"
HeaderStyle-BackColor="DarkBlue"
HeaderStyle-ForeColor="White"
HeaderStyle-Font-Italic="false"
>
</asp:GridView>
</div>
</form>
</body>
</html>