|
xxx
C# - Reading Access Data into DataGrid
by Charles Carroll
Here is code to read data from an Access Database and show it in a DataGrid.
filename=/experiments/training/cs/myfirstdb.aspx
<%@ Import Namespace="System.Data.OleDb" %>
<script language="C#" runat="server">
protected void Page_Load(Object Src, EventArgs E)
{
OleDbConnection Conn= null;
OleDbDataReader Rdr=null;
try
{
string strConn="PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=";
strConn += Server.MapPath (@"\experiments\data\biblio.mdb") + ";";
/*
Download data from http://www.learnasp.com/biblio
strConn += Server.MapPath (@"\experiments\data\biblio.mdb") + ";";
can be changed to:
strConn += Server.MapPath("biblio.mdb") + ";";
*/
string strSQL;
strSQL="select * from publishers where state='NY'";
Conn=new OleDbConnection(strConn);
OleDbCommand Cmd=new OleDbCommand(strSQL,Conn);
Conn.Open();
Rdr=Cmd.ExecuteReader();
// -or-
// Rdr=Cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
D1.DataSource = Rdr;
D1.DataBind();
} // end try
catch (Exception exc1)
{
litExc.Text=exc1.ToString();
} // end catch
finally
{
if (Rdr != null)
{
if (Rdr.IsClosed==false) {Rdr.Close();}
}
if (Conn != null)
{
if (Conn.State==System.Data.ConnectionState.Open) {Conn.Close();}
}
} // end finally
} // end page_load
</script>
<html><head><title>OLEDB Database Example</title></head>
<body bgcolor="#FFFFFF">
<font face="Verdana"><h3>My First Database Sample</h3></font>
<asp:literal id="litExc" runat="server" />
<ASP:DataGrid id="D1" runat="server" />
</body></html>
|