These are the minimum using directives to add at the top of the code behind for building an HTML table from a SQL Server to a SqlDataReader concisely.
[codesyntax lang=”csharp”]
using System.Web.UI.HtmlControls; using System.Data; using System.Data.SqlClient;
[/codesyntax]
Your table in the aspx file can be as simple as
[codesyntax lang=”html4strict”]
<table id="Products" runat="server"></table>
[/codesyntax]
And the code behind that does the work, taking the value from a dropdown list control called Category, and retrieving data from Northwind is
[codesyntax lang=”csharp”]
using(SqlConnection cnn = new SqlConnection("Data Source=YOURSERVER; Database=Northwind; UID=YOURDBUSERID; PWd=YOURDBPASSWORD")) { SqlCommand cmd; SqlDataReader rdr; HtmlTableRow row = new HtmlTableRow(); HtmlTableCell cell = new HtmlTableCell("th"); cell.InnerText = "Product ID"; row.Cells.Add(cell); cell = new HtmlTableCell("th"); cell.InnerText = "Product Name"; row.Cells.Add(cell); cell = new HtmlTableCell("th"); cell.InnerText = "Units in stock"; row.Cells.Add(cell); Products.Rows.Add(row); cmd = new SqlCommand("SELECT ProductID, ProductName, UnitsInStock FROM Products WHERE CategoryID = " + Category.SelectedValue, cnn); cnn.Open(); rdr = cmd.ExecuteReader(); while (rdr.Read()) { row = new HtmlTableRow(); cell = new HtmlTableCell(); cell.InnerText = rdr["ProductID"].ToString(); row.Cells.Add(cell); cell = new HtmlTableCell(); cell.InnerText = rdr["ProductName"].ToString(); row.Cells.Add(cell); cell = new HtmlTableCell(); cell.InnerText = rdr["UnitsInStock"].ToString(); row.Cells.Add(cell); Products.Rows.Add(row); } }
[/codesyntax]