|
Code-Behinds in C#
This simple example shows how to use code-behinds in ASP.NET. The following
code fills a dropdown box selecting data from the pubs database. This is an example
method of separating presentation from business logic.
Here is the code:
The webpage.
<%@ Page Language="C#" Debug="False"
Inherits="myCodeBehind" src="2.cs"%>
<html>
<head><title>Fill dropdown with C# and Sql
DataReader</title></head>
<body>
<asp:Dropdownlist
id="atMyDropDownList" DataValueField = "au_lname" DataTextField =
"au_id" runat="server" />
</body>
</html> |
The Code-behind page
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public class myCodeBehind : System.Web.UI.Page
{
public DropDownList atMyDropDownList;
private void Page_Load(object sender, System.EventArgs e)
{
string sqlText = "select * from
authors";
atMyDropDownList.DataSource = GetDr( sqlText );
atMyDropDownList.DataBind();
}
private SqlDataReader GetDr( string sqlText)
{
SqlDataReader dr;
SqlConnection sqlConn = new
SqlConnection(ConnectionString());
SqlCommand sqlCmd = new
SqlCommand(sqlText,sqlConn);
sqlCmd.Connection.Open();
dr =
sqlCmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
return dr;
}
private string ConnectionString()
{
return
ConfigurationSettings.AppSettings["DSN_pubs"];
}
private void Page_Init( object Sender, System.EventArgs e)
{
}//end Page_Init
} //End Class |
Web.Config holding application settings
<configuration>
<appSettings>
<add key="DSN_Northwind"
value="server=(local)\NetSDK;database=Northwind;Trusted_Connection=yes" />
<add key="DSN_pubs"
value="server=(local)\NetSDK;database=pubs;Trusted_Connection=yes" />
</appSettings>
</configuration> |
|
|