List Style Server Controls

As with ASP.Net 1.1, v2.0 List style server controls still share common properties, methods and events, but now they share even more. Because of the declarative style of design which is now implemented, they can also use the DataSource control to populate the lists instead of using code. Also, there is another List control presented here, the Bulleted List (like an HTML Select List). It’s functionality is much more than what is presented here, but this gives you a basic ‘first look’.

As you will see, they are sharing one DataSourceID for population data population. For this sample, the Northwind database is used, with a SQLDataSource control, and the Categories table is used.

<html>
	<head>
		<meta name="GENERATOR" Content="ASP Express 5.0">
		<title>List Style Server Controls</title>
	</head>
	<body>
		<form id="form1" Runat="server">
<table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor=#6397F8>
	<tr bgcolor="#BCD2FC">
		<td align="left" style="color:#000000"" valign="top">
			<asp:RadioButtonList ID="rbl" Runat="Server"
			DataTextField="CategoryName"
			DataValuefield="CategoryID"
			DataSourceID="ds1" />
		</td>
		<td align="left" style="color:#000000"" valign="top">
			<asp:CheckBoxList id="cbl" Runat="server"
			DataTextField="CategoryName"
			DataValuefield="CategoryID" DataSourceID="ds1" />
		</td>
		<td align="left" style="color:#000000"" valign="top">
			<asp:ListBox id="lb" Runat="server"
			DataTextField="CategoryName"
			DataValuefield="CategoryID" DataSourceID="ds1" />
		</td>
		<td align="left" style="color:#000000"" valign="top">
			<asp:DropDownList id="PutIDNameHere" Runat="server"
			DataTextField="CategoryName"
			DataValuefield="CategoryID" DataSourceID="ds1" />
		</td>
		<td align="left" style="color:#000000"" valign="top">
			<asp:BulletedList ID="BulletedList1" runat="server"
			DataTextField="CategoryName"
			DataValuefield="CategoryID" BulletStyle="Disc"
			 DataSourceID="ds1" />
		</td>
		<td align="left" style="color:#000000"" valign="top">
			<asp:BulletedList ID="BulletedList2" runat="server"
			DataTextField="CategoryName"
			DataValuefield="CategoryID" BulletStyle="Numbered"
			 DataSourceID="ds1" />
		</td>
	</tr>
</table>

<asp:SQLDataSource ID="ds1"
	 Runat="Server"
	 SelectCommand = "SELECT  CategoryID,  CategoryName From Categories"
	ConnectionString="YourConnectionStringGoesHere">
</asp:SQLDataSource>
		</form>
	</body>
</html>

Search from a Textbox-Display with a GridView

This sample shows several things, however, the main item shown is the procedure laid out in the title of the sample. In this sample, DS2 uses a ‘Like’ SQL Statement, in order for the user to type in a minimum numer of characters, for the search (here, like ‘bo’, ‘ch’, or ‘ant’).

Also, since there are two SQLDataSourceControls, here, we show how to assign the connectionstring to a variable, and programmatically change/assign the connectionstring in code. Along with that, we also show how to assign the Selectcommands for each, in code. Mainly, though, in this case, since the connectionstrings are lengthy, it helps to do this, in order to save screen width.

<script language="VB" Runat="server">
Dim sConn as String
Sub Page_Load(Source as Object, E as EventArgs)
sConn="server=YourServer;Database=YourDb;pwd=YourPWD;uid=YourUID"

DS1.SelectCommand = "SELECT  ProductID,  ProductName,  CategoryID,  " & _
"UnitsInStock,  UnitPrice From  dbo.NWProducts"
DS1.ConnectionString=sConn

DS2.SelectCommand = "Select [ProductID], [ProductName], [QuantityPerUnit], " & _
"[UnitPrice] from NWProducts Where ProductName LIKE ''%'' + @ProductName + ''%''"
DS2.ConnectionString=sConn
End Sub

Sub doSearch(Source as Object, E as EventArgs)
MyGridView.DataSourceID = "DS2"
MyGridView.DataBind()
End Sub

Sub doShowAll(Source as Object, E as EventArgs)
MyGridView.DataSourceID = "DS1"
MyGridView.DataBind()
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 5.0">
<title>Search from a Textbox - Display with a GridView</title>
</head>
<body>
<form id="form1" Runat="server">
Search by Product Name:
<asp:TextBox id="txtProduct" Runat="server" />
<asp:Button id="button1" Text="Search" onclick="doSearch" Runat="server" />
<asp:Button id="button2" Text="Show All" onclick="doShowAll" Runat="server" />
<asp:GridView Runat="server"
Id="MyGridView"
GridLines="None"
cellpadding="0"
cellspacing="1"
Headerstyle-BackColor="#7988B7"
Headerstyle-Forecolor="#FFFFFF"
Headerstyle-Font-Names="Arial"
Headerstyle-Font-Size="10"
BackColor="#E0E0F6"
Font-Names="Arial"
Font-Size="8"
AlternatingRowStyle-BackColor="#EFEFEF"
AlternatingRowStyle-Font-Names="Arial"
AlternatingRowStyle-Font-Size="8"
BorderColor="Black"
AllowPaging = "True"
PageSize = "10"
PagerSettings-Mode = "Numeric"
PagerStyle-HorizontalAlign="Center">
</asp:GridView>

<asp:SQLDataSource ID="DS1"
Runat="Server">
</asp:SQLDataSource>
<asp:SQLDataSource ID="DS2"
Runat="Server">
<SelectParameters>
<asp:ControlParameter
ControlID="txtProduct"
Name="ProductName"
PropertyName="Text"
Type="String"></asp:ControlParameter>
</SelectParameters>
</asp:SQLDataSource>
</form>
</body>
</html>

List of Queries – MS Access

This sample is pretty much like a previous sample, showing a list of tables in an MS Access database. This new sample was a request for a new sample, showing a list of MS Access saved Queries/Procedures.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
	Dim MyConn As New OleDbConnection()
	Dim schemaTable As DataTable
	Dim i As Integer
	MyConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
		server.mappath("\data\northwind.mdb") & ";"
	MyConn.Open()
	schemaTable = MyConn.GetOleDbSchemaTable(OleDbSchemaGuid.Procedures, _
		New Object() {Nothing, Nothing, Nothing})
	For i = 0 To schemaTable.Rows.Count - 1
		ListBox1.Items.Add(schemaTable.Rows(i)!PROCEDURE_NAME.ToString)
	Next i
	MyConn.Close()
End Sub
</script>
<html>
	<head>
		<meta name="GENERATOR" Content="ASP Express 5.0">
		<title>List of Queries/Procedures-MS Access</title>
	</head>
	<body>
		<form id="form1" Runat="server">
			<asp:ListBox id="ListBox1" Rows="8" Runat="server" />
		</form>
	</body>
</html>

Calendar – Recurring Events

This sample shows how to show recurring events in a calendar control. In this sample, every Sunday, our business wants you to know they’re closed, while on every Thursday, it’s ‘Half Price Night’.

<html>
<head>
<meta name="GENERATOR" Content="ASP Express 5.0">
<title>Calendar - Recurring Events</title>
<script language="VB" runat="server">
Sub Calendar_DayRender(sender As Object, e As DayRenderEventArgs)
Dim d As CalendarDay
Dim c As TableCell
Dim ThursString as String
Dim SunString as String
ThursString="<br><span style=""font-size:7pt;color:blue"">Half Price Night</span>"
SunString="<br><span style=""font-size:7pt;color:red"">Closed</span>"
d = e.Day
c = e.Cell
Dim ThisDay as DateTime=d.Date
if ThisDay.DayOfWeek.ToString ="Sunday" then
c.Controls.Add(new LiteralControl(SunString))
End If
if ThisDay.DayOfWeek.ToString ="Thursday" then
c.Controls.Add(new LiteralControl(ThursString))
End If
End Sub
</script>
</head>
<body>
<Form id="form1" runat="server">
<asp:Calendar runat="server"
id="calendar1"
Backcolor="White"
Forecolor="Black"
Borderwidth="2"
Width="100%"
ShowGridLines="true"
ondayrender="Calendar_DayRender"
SelectedDayStyle-Backcolor="#DEEFFF"
SelectedDayStyle-forecolor="Black"
TitleStyle-BackColor="#DEEFFF"
TitleStyle-Font-Bold="True"
TitleStyle-Height="36px"
OtherMonthDayStyle-ForeColor="gray"
TodayDayStyle-Font-Bold="True"
TodayDayStyle-Font-Italic="True"
TodayDayStyle-Font-Size="12pt"
DayHeaderStyle-Font-Bold="True"
DayHeaderStyle-BackColor="LightGray" />
</form>
</body>
</html>

GridView Select Button (Changed and Changing)

This code sample shows further use of the Select button in the GridView. Here, we’re looking at two specific events – OnSelectedIndexChanging and OnSelectedIndexChanged.

At first, they might look quite the same, but having both is quite handy. First, we’ll look at the OnSelectedIndexChanged event. Using this event, tells the page what to do once the Row Selection is totally complete. We add a sub called ‘GVChanged’ and reference it in the tag itself. In this sub, the code here looks at the row that was selected, and creates text for Label1 accordingly.

Now, let’s say we need to check the item which is selected, and based on certain criteria, make a coding decision. Here, we look at the UnitsInStock and, if there are no items in stock, add text to Label1 to reflect that.

<script language="VB" Runat="server">
Sub GVChanged(Source as Object, E as EventArgs)
Dim row As GridViewRow = MyGridView.SelectedRow
label1.text="You Chose - " & row.Cells(2).Text & ". There are " & _
row.Cells(3).Text & " in stock"
End Sub
Sub GVChanging(Source as Object, E as GridViewSelectEventArgs)
Dim row As GridViewRow = MyGridView.Rows(e.NewSelectedIndex)
if row.Cells(3).text="0" then
e.cancel="True"
label1.text="Sorry - " & row.Cells(2).text & " is out of Stock"
End If
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 5.0">
<title>GridView Select Button (Changed and Changing)</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:GridView Runat="server"
Id="MyGridView"
GridLines="None"
cellpadding="0"
cellspacing="1"
Headerstyle-BackColor="#7988B7"
Headerstyle-Forecolor="#FFFFFF"
Headerstyle-Font-Names="Arial"
Headerstyle-Font-Size="8"
BackColor="#E0E0F6"
Font-Names="Arial"
Font-Size="8"
BorderColor="Black"
onselectedindexchanged="GVChanged"
onselectedindexchanging="GVChanging"
AutoGenerateSelectButton="True"
DataSourceID="DS1">
</asp:GridView>

<asp:SQLDataSource ID="DS1"
Runat="Server"
SelectCommand = "SELECT Top 10 ProductID, ProductName, UnitsInStock from Products"
ConnectionString="<%$ ConnectionStrings:YourConnStringGoesHere %>">
</asp:SQLDataSource>
<asp:Label ID="label1" Runat="server" />
</form>
</body>
</html>

GridView with MySQL and Paging (no DataSource Control)

This sample, is based on and is almost exactly like the previous MySQL/ASP.Net DataGrid example. However, there are some subtle changes, like the syntax in the tag, which is changed to ‘OnPageIndexChanging’, and the Subroutine signature, which as changed from ‘DataGridPageChangedEventArgs’ to ‘GridViewPageEventArgs’.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.ODBC" %>
<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
Dim strConn as string
strConn = "DRIVER={MySQL};SERVER=Your_Srvr;DATABASE=Your_DB;USER=YourUid;PASSWORD=YourPWD;OPTION=3;"
Dim MySQL as string = "Select CustomerID, CompanyName, ContactTitle, " & _
"Address, City, Phone from Customers"
Dim MyConn as New ODBCConnection(strConn)
Dim ds as DataSet=New DataSet()
Dim Cmd as New ODBCDataAdapter(MySQL,MyConn)
Cmd.Fill(ds,"Customers")
gvCustomers.Datasource=ds.Tables("Customers").DefaultView
gvCustomers.DataBind()
End Sub

Sub PageIndexChanging(sender as Object,  e as GridViewPageEventArgs)
gvCustomers.PageIndex = e.NewPageIndex
gvCustomers.DataBind()
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 5.0">
<title>GridView with MySQL and Paging (no DataSource Control)</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:GridView Runat="server"
Id="gvCustomers"
GridLines="Both"
Border-Width="1"
cellpadding="2"
cellspacing="0"
Headerstyle-BackColor="#7988B7"
Headerstyle-Forecolor="#FFFFFF"
Headerstyle-Font-Names="Arial"
Headerstyle-Font-Size="8"
BackColor="#E0E0F6"
Font-Names="Arial"
Font-Size="8"
AllowPaging="True"
OnPageIndexChanging="PageIndexChanging"
BorderColor="Black">
</asp:GridView>
</form>
</body>
</html>

Disabling/Enabling Controls w/Checkbox

Sometimes it becomes necessary to enable or disable a controls, or group of controls on a web page, based on choices made in that page. Controls which could govern this type of change include Checkboxes or RadioButtons, for example. Naturally, if there were multiple controls which need to be enabled or disabled in this manner, it would be better to put them all in a container control, like the Panel.

This sample shows how to do this, using 2 checkboxes. Using the ‘OnCheckChanged’ event of the Checkbox, it’s very easy to get this scenario setup quickly.

<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
EnableCheckBox
End Sub

Sub doIt(Source as Object, E as EventArgs)
EnableCheckBox
End Sub

Sub EnableCheckBox()
if chk1.checked="True" then
chk2.Enabled="True"
else
chk2.enabled="False"
End If
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 5.0">
<title>Disabling/Enabling Controls w/Checkbox</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:Checkbox Text="Check box #1" id="chk1" AutoPostBack="true"
OnCheckedChanged="doIt" Runat="server" />
<asp:Checkbox Text="Check box #2" id="chk2" Runat="server" />
</form>
</body>
</html>

DetailsView Paging/Using a TemplateField

A website user requested this particular sample. Here, we use a DetailsView control (along with a SQLDataSource control), to page from record to record. The PagerStyle Mode is set to ‘NextPreviousFirsLast’, in this case, but there are several different ways to do this.

Along with this, we show how to use a TemplateField to allow a Multiline textbox to be used during the editing process, with an EditItemTemplate. A label is used for the normal InsertItemTemplate.

<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
DS1.SelectCommand = "SELECT EmployeeID, LastName, FirstName, " & _
"Title, BirthDate, HireDate, Address, City, Region, PostalCode, Country, " & _
"HomePhone, Extension, Notes, ReportsTo From dbo.Employees"
DS1.UpdateCommand="Update Employees Set LastName=@LastName, " & _
"FirstName=@FirstName, Title=@Title, BirthDate=@BirthDate, HireDate=@HireDate, " & _
"Address=@Address, City=@City, Region=@Region, PostalCode=@PostalCode, " & _
"Country=@Country, HomePhone=@HomePhone, Extension=@Extension, " & _
"Notes=@Notes Where EmployeeID=@EmployeeID"
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 5.0">
<title>DetailsView Paging and TemplateField</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:DetailsView Runat="server"
Id="MyDetailsView"
GridLines="None"
cellpadding="0"
cellspacing="1"
Headerstyle-BackColor="#7988B7"
Headerstyle-Forecolor="#FFFFFF"
Headerstyle-Font-Names="Arial"
Headerstyle-Font-Size="8"
BackColor="#E0E0F6"
Font-Names="Arial"
Font-Size="8"
AutoGenerateEditButton="True"
BorderColor="Black"
AllowPaging = "True"
PageSize = "10"
PagerSettings-Mode = "NextPreviousFirstLast"
PagerSettings-Position="Bottom"
PagerStyle-HorizontalAlign="Center"
DataKeyNames="EmployeeID"
DataSourceID="DS1"
Width="50%"
AutogenerateRows="False">
<Fields>
<asp:BoundField DataField="EmployeeID" SortExpression="EmployeeID"
HeaderText="EmployeeID" ReadOnly="True"/>
<asp:BoundField DataField="FirstName" SortExpression="FirstName" HeaderText="FirstName"/>
<asp:BoundField DataField="LastName" SortExpression="LastName" HeaderText="LastName"/>
<asp:BoundField DataField="Title" SortExpression="Title" HeaderText="Title"/>
<asp:BoundField DataField="BirthDate" SortExpression="BirthDate" HeaderText="BirthDate"/>
<asp:BoundField DataField="HireDate" SortExpression="HireDate" HeaderText="HireDate"/>
<asp:BoundField DataField="Address" SortExpression="Address" HeaderText="Address"/>
<asp:BoundField DataField="City" SortExpression="City" HeaderText="City"/>
<asp:BoundField DataField="Region" SortExpression="Region" HeaderText="Region"/>
<asp:BoundField DataField="PostalCode" SortExpression="PostalCode" HeaderText="PostalCode"/>
<asp:BoundField DataField="Country" SortExpression="Country" HeaderText="Country"/>
<asp:BoundField DataField="HomePhone" SortExpression="HomePhone" HeaderText="HomePhone"/>
<asp:BoundField DataField="Extension" SortExpression="Extension" HeaderText="Extension"/>
<asp:TemplateField HeaderText="Notes">
<ItemTemplate>
<asp:Label ID="lblNotes" Text=''<%# Bind("Notes") %>'' Runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox id="txtNotes" Rows="5" Columns="50"
Runat="server" TextMode="MultiLine" Text=''<%# Bind("Notes") %>'' />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ReportsTo" SortExpression="ReportsTo" HeaderText="ReportsTo"/>
</Fields>
</asp:DetailsView>

<asp:SQLDataSource ID="DS1"
Runat="Server"
ConnectionString="<%$ ConnectionStrings:YourSettingGoesHere %>">
</asp:SQLDataSource>
</form>
</body>
</html>

GridView – Export to Excel (VB.Net)

This sample uses the Products table of the Northwind Database to show how to export a Gridview’s rows to an Excel Spreadsheet, using VB.Net,

There are a couple of ‘tricks’ used here, in order to get this done. First, we dynamically create a form and populate the Controls collection with it, and then populate the form with the GridView. Before, in the DataGrid sample, this wasn’t necessary, as we could use the Rendercontrol method directly.

Next, in order to get the full results in the spreadsheet, we temporarily ‘turn off’ paging (also necessary if sorting was on), otherwise, it would return errors. Lastly, [FieldList] is used in place of the actual list of fields in the SelectCommand, specifically for saving horizontal screen real estate.

<%@ Import Namespace="System.IO" %>
<script language="VB" Runat="server">
Sub doExcel(Source as Object, E as EventArgs)
If gv.Rows.Count.ToString + 1 < 65536 Then
gv.AllowPaging="False"
gv.DataBind
Dim tw As New StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim frm As HtmlForm = new HtmlForm()
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("content-disposition", "attachment;filename=" & txtFile.text & ".xls")
Response.Charset = ""
EnableViewState = False
Controls.Add(frm)
frm.Controls.Add(gv)
frm.RenderControl(hw)
Response.Write(tw.ToString())
Response.End()
gv.AllowPaging="True"
gv.Databind
Else
LblError.Text="Too many rows - Export to Excel not possible"
End If
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 5.0"/>
<title>Export GridView to Excel</title>
</head>
<body>
<form id="fm1" runat="server">
Enter File Name:
<asp:TextBox id="txtFile" Text="MyExcelFile" Runat="server" />
<asp:GridView Runat="server"
Id="gv"
GridLines="None"
cellpadding="0"
cellspacing="1"
Headerstyle-BackColor="#7988B7"
Headerstyle-Forecolor="#FFFFFF"
Headerstyle-Font-Names="Arial"
Headerstyle-Font-Bold="True"
Headerstyle-Font-Size="11"
BackColor="#E0E0F6"
Font-Names="Arial"
Font-Size="10"
AlternatingRowStyle-BackColor="#EFEFEF"
AlternatingRowStyle-Font-Names="Arial"
AlternatingRowStyle-Font-Size="10"
BorderColor="Black"
DataKeyNames="ProductID"
DataSourceID="sqlProducts"
AllowPaging="True"
AutogenerateColumns="False">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ID" ReadOnly="True"/>
<asp:BoundField DataField="ProductName" HeaderText="Name"/>
<asp:BoundField DataField="SupplierID" HeaderText="SupplierID"/>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID"/>
<asp:BoundField DataField="QuantityPerUnit" HeaderText="Quantity"/>
<asp:BoundField DataField="UnitPrice" HTMLEncode="False" DataformatString="{0:c}" HeaderText="Price"/>
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock"/>
</Columns>
</asp:GridView>
<asp:Button id="btn" Text="Get It" onclick="doExcel" Runat="server" />
<p>
<asp:Label ID="LblError" Runat="server" />
</p>
<asp:SQLDataSource ID="sqlProducts"
Runat="Server"
SelectCommand = "SELECT [FieldList] From NWProducts"
ConnectionString="<%$ ConnectionStrings: %>">
</asp:SQLDataSource>
</form>
</body>
</html>

Using an ImageField in a GridView

In this sample, we are using an MS Access Database, with an AccessDataSource control, to show how to use the ImageField in a GridView. Instead of storing an image in the database, we actually store the path, relative to the page itself, in a field in the table. Then, in the ‘DataImageURLField’ property of the ImageField control, we reference that path. In this case the actual field name is called ‘ImgPath’.

<pre>

<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 5.0″>
<title>Using an ImageField in a GridView</title>
</head>
<body>
<form id=”form1″ Runat=”server”>
<asp:GridView Runat=”server”
Id=”MyGridView”
GridLines=”Both”
Border-Width=”1″
cellpadding=”0″
cellspacing=”1″
Headerstyle-BackColor=”#7988B7″
Headerstyle-Forecolor=”#FFFFFF”
Headerstyle-Font-Names=”Arial”
Headerstyle-Font-Size=”8″
BackColor=”#E0E0F6″
Font-Names=”Arial”
Font-Size=”8″
BorderColor=”Black”
DataSourceID=”AccDS1″
DataKeyNames=”id”
AutogenerateColumns=”False”>
<Columns>
<asp:BoundField DataField=”id” HeaderText=”id” ReadOnly=”True”/>
<asp:BoundField DataField=”ProdName” HeaderText=”ProdName”/>
<asp:ImageField DataImageURLField=”ImgPath” />
<asp:BoundField DataField=”Comments” HeaderText=”Comments”/>
</Columns>
</asp:GridView>
<asp:AccessDataSource ID=”AccDS1″
Runat=”Server”
SelectCommand = “SELECT id, ProdName, ImgPath, Comments From Products”
DataFile=”\data\products.mdb”>
</asp:AccessDataSource>
</form>
</body>
</html></pre>