Introducing ADO.NET with ASP.NET 2.0 - Populating a ListBox control from the Northwind database
(Page 2 of 4 )
For this example we will populate a ListBox control with data from the Employees table of the Northwind database. We will select only the FirstName and the LastName columns from the Employees table, and add the rows as list items to the ListBox control. Let's do it. Start by creating a new website: File --> New --> Website, and place the website folder on the file system. Drag a ListBox control on the page and set its width to 157 and its height to 143 (pixels). That's all that you need in the Default.aspx file.
The following is the code of the Default.aspx.cs file (you need to replace the auto-generated code template with the following code or write it by hand step by step):
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
// use the namespace of the ADO.NET SQL Server Data Provider
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// create the connection and set the connection string
// through the connection object's ConnectionString property
SqlConnection connection = new SqlConnection();
string connectionString = "Data Source=(local);Initial
Catalog=Northwind;Integrated Security=True";
connection.ConnectionString = connectionString;
// create the command object and assign the connection object to
it
// through the Connection property
SqlCommand command = new SqlCommand();
command.Connection = connection;
// creating the T-SQL SELECT statement and assign it to the
command
// through the CommandText property
string commandText = "SELECT LastName, FirstName FROM
Employees";
command.CommandText = commandText;
// assigning the value CommandType.Text to the CommandType
property
// because we are using a T-SQL statement not a stored procedure
command.CommandType = CommandType.Text;
// we have initialized the connection and the command so it's
time
// to open the connection and execute the command
connection.Open();
// get a SqlDataReader object from the Command's ExecuteReader()
method
SqlDataReader dataReader = command.ExecuteReader();
// adding the returned rows to the listbox control
while(dataReader.Read())
{
ListBox1.Items.Add(dataReader[0] + ", " + dataReader[1]);
}
dataReader.Close();
connection.Close();
}
}
Now run the page and you will get the first names and last names of the employees added to the list box control as shown in the following screenshot.

Next: Explaining the code >>
More ASP.NET Articles
More By Michael Youssef