<%@ Page EnableSessionState="False" EnableViewState="False" Debug="False" Trace="False" strict="True" %> <%@ Import Namespace="System.Data" %> <%@ Import NameSpace="System.Data.SqlClient" %> <script language="vb" runat="server"> Sub Page_Load(sender as Object, e as EventArgs) Dim i, k As Integer dim theSQL as string = "SELECT au_id, au_lname, au_fname, phone, address, " & _ "city, state, zip, contract FROM Authors" 'I don't ever embed the connection string inside aspx page. 'Use the System.Configuration class to extract 'the value from the appSettings Dim myConn as SqlConnection = new SqlConnection(ConfigurationSettings.AppSettings("DSN_pubs")) dim ds as dataset = new dataset() dim dt as datatable dim adapter as sqldataadapter = new SqlDataAdapter(theSQL, myConn)
myConn.Open() adapter.Fill(ds,"DataTable") myConn.Close()
dt = ds.Tables("DataTable")
'Set two variables to the number of rows and columns the datatable has Dim RowCount As Integer = dt.rows.count Dim ColCount As Integer = dt.Columns.Count
'Loop through the datatable to format the output Dim sb as StringBuilder = New StringBuilder() sb.append( "<table border='1' width='80%'>" ) For i = 0 To RowCount - 1 sb.Append("<tr>") For k = 0 To ColCount - 1 sb.Append("<td>") sb.Append( dt.Rows(i).Item(k, DataRowVersion.Current).toString()) sb.Append( "</td>" ) Next sb.Append("<tr>") Next sb.Append( "</table>")
'Output to the Label control that will show the output Dim strOutput as String = sb.ToString() lblCompany.Text = strOutput 'Uses a hyperlink server control to display a link returnHome.NavigateUrl = "/aspnet/Default.aspx" End Sub </script> <html> <head><title>Using StringBuilder Class</title></head> <body> <asp:hyperlink id=returnHome runat="server"> Back to the Article </asp:hyperlink> <asp:label id="lblCompany" runat="server" /> </body> </html> Web.Config that holds the connection string <configuration> <appSettings> <add key="DSN_pubs" value="server=localhost;uid=sa;pwd=;database=pubs" /> </appSettings> </configuration> |