How to Display Data using the .NET CheckBoxList Control, ASP.NET 2.0 and VB.NET
This tutorial will show you how to display data using the .NET CheckBoxList Control, ASP.NET 2.0 and VB.NET
The .NET Framework offers a number of classes that makes populating controls with data easy.
We will need to first import the System.Data.SqlClient namespace. The System.Data.SqlClient namespace contains the methods we will need to query our SQL database.
| Imports System.Data.SqlClient |
We'll put our code in the btnSubmit_Click() event.
When the btnSubmit_Click() event fires it queries our database and creates a new SqlDataReader by invoking the ExecuteReader() method of our cmd object. We make sure to specify the DataTextField property so the CheckBoxList control will know which columns to display as a list.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try Dim cmd As SqlCommand = New SqlCommand("SELECT TOP 5 firstname,lastname,hiredate FROM EMPLOYEES", New SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=True;")) cmd.Connection.Open() Dim datareader As SqlDataReader = cmd.ExecuteReader() chkBoxEx.DataSource = datareader chkBoxEx.DataTextField = "firstname" chkBoxEx.DataBind() cmd.Connection.Close() cmd.Connection.Dispose() Catch ex As Exception lblStatus.Text = ex.Message End Try End Sub
|
The front end .aspx page looks something like this:
<table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#cccccc"> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1" style='height: 62px'> Employee Data Populating A CheckBoxList Control:</td> <td align="center" bgcolor="#FFFFFF" style='height: 62px'> <asp:CheckBoxList ID="chkBoxEx" runat="server"> </asp:CheckBoxList><asp:label ID="lblStatus" runat="server"></asp:label></td> </tr> </table> |
The flow for the code behind page is as follows.
Imports System.Data.SqlClient Partial Class _Default Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try Dim cmd As SqlCommand = New SqlCommand("SELECT TOP 5 firstname,lastname,hiredate FROM EMPLOYEES", New SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=True;")) cmd.Connection.Open() Dim datareader As SqlDataReader = cmd.ExecuteReader() chkBoxEx.DataSource = datareader chkBoxEx.DataTextField = "firstname" chkBoxEx.DataBind() cmd.Connection.Close() cmd.Connection.Dispose() Catch ex As Exception lblStatus.Text = ex.Message End Try End Sub End Class
|