Limit Characters in MultiLine Textbox

Sometimes, it becomes necessary to limit the number of characters entered into a TextArea (multiLine TextBox in ASP.Net), however, this functionality is not built in. When the TextBox TextMode is set to ‘MultiLine’, the ‘MaxLength’ property does not work.

However, with Javascript, it can easily be done. With this JS routine, the end-user can see just how many characters are left, as he keys in comments.

<script language=JavaScript>
<!-- Beginning of JavaScript -
function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit) {
		field.value = field.value.substring(0, maxlimit);
	} else {
		countfield.value = maxlimit - field.value.length;
	}
}
//  End -->>
</script>
<html>
	<head>
		<meta name="GENERATOR" Content="ASP Express 4.5">
		<title>Untitled</title>
	</head>
	<body>
		<form id="form1" Runat="server">
			Characters Left:
				<asp:TextBox
					BackColor="Blue"
					BorderStyle="None"
					Width="30"
					ForeColor="White"
					Font-Bold="True"
					id="txtLen"
					Runat="server" Text="100" /><br>
			Enter comments:<br>
			<asp:TextBox id="txtmessage"
				Columns="40" Rows="4"
				TextMode="MultiLine"
				onkeydown="textCounter(this.form.txtmessage,this.form.txtLen,100)"
				onkeyup="textCounter(this.form.txtmessage,this.form.txtLen,100)"
				Runat="server" />
		</form>
	</body>
</html>

Exporting DataGrid Results to Excel File

With this sample, we show how to export the results of a Datagrid, locally, to an Excel file, assuming, of course, Excel is installed on the computer.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
	Dim strConn as string = "server=YourServer;uid=yourUID;pwd=YourPWD;database=Northwind"
	Dim mySQL as string = "Select Top 10 * from Products"
	Dim con as New SQLConnection(strConn)
	Dim ds as DataSet=New DataSet()
	Dim Cmd as New SQLDataAdapter(mySQL,con)
	Cmd.Fill(ds,"Products")
	MyDataGrid.Datasource=ds.Tables("Products").DefaultView
	MyDataGrid.DataBind()
End Sub

Sub doExport(Source as Object, E as EventArgs)
	RenderGridToExcelFormat(MyDataGrid,txtfilename.text)
End Sub

        Sub RenderGridToExcelFormat(grid As DataGrid, saveAsFile As String)
            '' Excel rows limit is 65536
            If grid.Items.Count.ToString + 1 < 65536 Then
                HttpContext.Current.Response.Clear()
                HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" & saveAsFile & ".xls")
                '' Remove the charset from the Content-Type header.
                HttpContext.Current.Response.Charset = ""
                ''HttpContext.Current.Response.WriteFile("style.txt")
                '' Turn off the view state.
                grid.EnableViewState = False
                Dim tw As New System.IO.StringWriter()
                Dim hw As New System.Web.UI.HtmlTextWriter(tw)
                grid.RenderControl(hw)
                '' Write the HTML back to the browser.
                HttpContext.Current.Response.Write(tw.ToString())
                '' End the response.
                HttpContext.Current.Response.End()
            Else
                HttpContext.Current.Response.Write("Too many rows - Export to Excel not possible")
            End If
        End Sub
</script>
	<!-- Created: 9/7/2005 1:51:46 PM -->
<html>
	<head>
		<meta name="GENERATOR" Content="ASP Express 4.1.2">
		<title>Untitled</title>
	</head>
	<body>
		<form id="form1" Runat="server">
<asp:Datagrid Runat="server"
	Id="MyDataGrid"
	GridLines="None"
	cellpadding="0"
	cellspacing="1"
	Headerstyle-BackColor="#0000FF"
	Headerstyle-Forecolor="#FFFFFF"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="8"
	BackColor="#F5F5F5"
	Font-Name="Arial"
	Font-Size="8"
	BorderColor="Black">
</asp:DataGrid>
<br>Enter Filename (don''t add ''.xls''):<br>
<asp:TextBox id="txtFilename" Runat="server" />
<asp:Button id="button1" Text="Export" onclick="doExport" Runat="server" />
		</form>
	</body>
</html>

Master Detail #2 – DDL with DataGrid

In this sample, we use the Northwind Database to populate a DropDownList with the different Categories of products which the Northwind Company sells. Then, by choosing a category from the DropDownList, when the button is clicked, a DataGrid is filled with the products in that particular category.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
	if not Page.IsPostBack then
		Dim strConn as string = ConfigurationSettings.AppSettings("YourDBSettings")
		Dim MySQL as string = "Select [Categories].[CategoryID], " & _
		"[Categories].[CategoryName] from Categories"
		Dim MyConn as New SQLConnection(strConn)
		Dim objDR as SQLDataReader
		Dim Cmd as New SQLCommand(MySQL, MyConn)
		MyConn.Open()
		objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
		ddlCategories.DataSource = objDR
		ddlCategories.DataValueField="categoryID"
		ddlCategories.DataTextField="CategoryName"
		ddlCategories.DataBind()
		MyConn.Close()
	end if
End Sub

Sub GetProducts(Source as Object, E as EventArgs)
	Dim strConn as string = ConfigurationSettings.AppSettings("YourDBSettings")
	Dim MySQL as string = "Select [Products].[ProductID], [Products].[ProductName], " & _
	"[Products].[UnitPrice], [Products].[UnitsInStock] from Products " & _
	"Where Products.CategoryID = @CategoryID"
	Dim MyConn as New SQLConnection(strConn)
	Dim objDR as SQLDataReader
	Dim Cmd as New SQLCommand(MySQL, MyConn)
	With cmd.Parameters:
		.Add(New SQLParameter("@CategoryID", ddlCategories.SelectedItem.Value))
	End With
	MyConn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	dgProducts.DataSource = objDR
	dgProducts.DataBind()
	MyConn.Close()
End Sub
</script>
<html>
	<head>
		<meta name="GENERATOR" Content="ASP Express 4.0">
		<title>Untitled</title>
	</head>
	<body>
		<form id="form1" Runat="server">
			<asp:DropDownList id="ddlCategories" Runat="server">
			</asp:DropDownList> <asp:Button id="btnCategories"
				Text="Get Products" onclick="GetProducts" Runat="server" />
			<asp:Datagrid Runat="server"
				Id="dgProducts"
				GridLines="Both"
				cellpadding="0"
				cellspacing="0"
				Headerstyle-BackColor="#0000FF"
				Headerstyle-Forecolor="#FFFFFF"
				Headerstyle-Font-Name="Arial"
				Headerstyle-Font-Size="8"
				BackColor="#ADDEF5"
				Font-Name="Arial"
				Font-Size="8"
				BorderColor="Black">
			</asp:DataGrid>
		</form>
	</body>
</html>

Calculating a Person's Age

In this sample, the user will select a birth date, using Day, Month and Year Dropdownlists. Then, when the button is clicked, based on the current date, the age of the person whose birth date was chosen, will be calculated and displayed.

<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 4.0beta">
	<title>Calculating a Person''s Age</title>
<script language="vb" runat="server">
Dim x As Integer
Dim intDay, intMnth as integer
Dim MyDate as DateTime
Dim arr as ArrayList
Dim myYear as Integer
Sub Page_Load(sender As Object, e As EventArgs)

if not Page.IsPostBack then
	intDay=Day(now)
	intMnth = Month(Now)
	Dim MyDate as DateTime
	MyDate=DateTime.Now
	If Not IsPostBack Then
		For x = 1 To 12
			ddMonth.Items.Add(New ListItem(MonthName(x), x))
		Next

		For x=1 to 31
			ddDay.Items.Add(x)
		Next
		End If
		arr=New Arraylist

		''Next two For/Next Loops add 75 years before current year
		For x = 0 to 75
			arr.add(MyDate.Year-x)
		Next

		arr.Sort
		ddYear.DataSource=arr
		ddYear.DataBind

	ddDay.selectedIndex=intDay-1
	ddMonth.selectedIndex=intMnth-1
	ddYear.Items.FindByValue(MyDate.Year).Selected = true
end if
end sub

Sub getDiff(Source as Object, E as EventArgs)
	Dim myBirth as DateTime
	Dim sDate as String
	Dim Age As Integer
	sDate=ddMonth.SelectedItem.Value & "/" & ddDay.SelectedItem.Text & "/" & ddYear.SelectedItem.Text
	myBirth=cDate(sDate)
	Age=DateTime.Now.Year - myBirth.Year
	If DateTime.Now.Month < myBirth.Month Or (DateTime.Now.Month = myBirth.Month And DateTime.Now.Day < myBirth.Day) Then
	    Age = Age - 1
	End If
	lblDate.text="Age=" & Age.ToString
End Sub

Sub doDayChange(Source as Object, E as EventArgs)
dayChange
End Sub

Sub dayChange()
if MyYear.ToString.length < 4  then
	MyYear=MyDate.Year
else
	MyYear=ddYear.SelectedItem.Text
End If

MyDate=ddMonth.SelectedItem.Text & "/1/" &  myYear
	ddDay.Items.Clear()
	For x = 1 To MyDate.DaysInMonth(MyDate.Year, MyDate.Month)
		ddDay.Items.Add(x)
	Next
End Sub

Sub doYear(Source as Object, E as EventArgs)
myYear = ddYear.selectedItem.Text
dayChange
End Sub
</script>
</head>
<HTML>
<body>
<form id="Form1" method="post" runat="server">
<b><i>Choose Birth Date:</i></b>
<table>
	<tr>
		<td align="Left" valign="Top">
			<b>Month:</b></td>
		<td align="Left" valign="Top">
			<b>Day:</b</td>

		<td align="Left" valign="Top">
			<b>Year:</b></td>
	</tr>
	<tr>
		<td align="Left" valign="Top">

			<asp:DropDownList
				ID="ddMonth"
				Runat="server">
			</asp:DropDownList></td>
		<td align="Left" valign="Top">
			<asp:DropDownList
				ID="ddDay"
				Runat="server">
			</asp:DropDownList> </td>
		<td align="Left" valign="Top">
			<asp:DropDownList
				id="ddYear"
				Runat="server">
			</asp:DropDownList> <asp:Button id="btnGetDiff" Text="Get Age" onclick="getDiff" Runat="server" /><br></td>
	</tr>
	<tr>
		<td align="Center" valign="Top" Colspan="3">
			<asp:Label ID="lblDate" Font-Bold="True" Runat="server" />
		</td>
	</tr>
</table>
</form>
</body>
</html>

Conditional Row Backcolors with a DataGrid

This sample shows you how to change the backcolor on certain rows, based on criteria presented within that row. Here, we use the Employees table from the pubs database. In each row, we check the hire date. If the date is BEFORE 1/1/1990, then we change the backcolor, programmatically, to light green.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<%@ Import Namespace="System.Drawing" %>
<script language="VB" Runat="server">
Dim strConn as string
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
		strConn = ConfigurationSettings.AppSettings("YourConnectionString")
		Dim MySQL as string = "Select * from Employee"
		Dim MyConn as New SQLConnection(strConn)
		Dim ds as DataSet=New DataSet()
		Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
		Cmd.Fill(ds,"Employees")
		dgPublishers.Datasource=ds.Tables("Employees").DefaultView
		dgPublishers.DataBind()
end if
End Sub

Sub CheckData(sender As Object, e As DataGridItemEventArgs)
Dim sDate as DateTime
if e.Item.ItemType.ToString="Item" or e.Item.ItemType.ToString="AlternatingItem"
	sDate=e.Item.Cells(7).text
	if sDate< "1/1/1990" then
		e.Item.Backcolor = Color.FromName("lightgreen")
	End If
End If
End Sub
</script>
<html>
	<head>
		<meta name="GENERATOR" Content="ASP Express 4.0">
		<title>Conditional Row Backcolors with a DataGrid</title>
</head>
	<body>
		<form id="form1" Runat="server">
			<div align="center">
			<asp:Label ID="label1" ForeColor="Blue" Font-Bold="True" Runat="server" />
				<asp:Datagrid Runat="server"
					Id="dgPublishers"
					GridLines="Both"
					cellpadding="0"
					cellspacing="0"
					Headerstyle-BackColor="#BDCFE7"
					Headerstyle-Font-Name="Arial"
					Headerstyle-Font-Size="8"
					BackColor="#E7EFFF"
					Font-Name="Arial"
					Font-Size="8"
					BorderColor="Black"
					OnItemDataBound="CheckData">
				</asp:DataGrid>
			</div>
		</form>
	</body>
</html>

Conditional AutoChecking Checkboxes with a DataGrid

Scenario – DataGrid with Checkboxes – we want the checkboxes automatically checked, based on the data from a particular column in the Database.

For this sample, we have a simple table called TestItems, with a PK – ‘ID’, a Name column and a column titled ‘TrueFalse’.

In the TrueFalse column (you guessed it) – we have only two possible values – either ‘True’ or ‘False’. We assign the Checked property of the checkbox to the value of the TrueFalse column. It will automatically check it if the value for that row is ‘True’, and not check it if the value is ‘False’.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
	Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=YourDB"
	Dim MySQL as string = "Select Name, TrueFalse from TestItems"
	Dim Myconn as New SQLConnection(strConn)
	Dim ds as DataSet=New DataSet()
	Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
	Cmd.Fill(ds,"TestItems")
	dgNames.Datasource=ds.Tables("TestItems").DefaultView
	dgNames.DataBind()
End If
End Sub
</script>
<html>
	<head>
		<meta name="GENERATOR" Content="ASP Express 4.0">
		<title>Conditional AutoChecking Checkboxes with a DataGrid</title>
</head>
	<body>
		<form id="form1" Runat="server">
			<div align="center">
				<asp:Datagrid Runat="server"
					Id="dgNames"
					GridLines="Both"
					cellpadding="0"
					cellspacing="0"
					Headerstyle-BackColor="#BDCFE7"
					Headerstyle-Font-Name="Arial"
					Headerstyle-Font-Size="8"
					BackColor="#E7EFFF"
					Font-Name="Arial"
					Font-Size="8"
					BorderColor="Black"
					AutogenerateColumns="False">
					<Columns>
						<asp:TemplateColumn HeaderText="Select">
							<ItemTemplate>
								<asp:Checkbox id="ck1"
									Checked=''<%# Container.DataItem("TrueFalse") %>''
									Runat="server" />
							</ItemTemplate>
						</asp:TemplateColumn>
						<asp:BoundColumn DataField="Name" HeaderText="Name">
						</asp:BoundColumn>

					</Columns>
				</asp:DataGrid>
			</div>
		</form>
	</body>
</html>

List of Tables – MS Access

This sample shows a way, using the OleDb Namespace, to retrieve the Tablenames and add them to a ListBox. Naturally, you can change the control to any other control or display device you’d like.

Remember, to just change the name of the relative path to the database you would like to use.

<%@ 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.Tables, _
		New Object() {Nothing, Nothing, Nothing, "TABLE"})
	For i = 0 To schemaTable.Rows.Count - 1
		ListBox1.Items.Add(schemaTable.Rows(i)!TABLE_NAME.ToString)
	Next i
	MyConn.Close()
End Sub
</script>
<html>
	<head>
		<meta name="GENERATOR" Content="ASP Express 4.0">
		<title>Untitled</title>
	</head>
	<body>
		<form id="form1" Runat="server">
			<asp:ListBox id="ListBox1" Rows="8" Runat="server" />
		</form>
	</body>
</html>

Conditional Checkboxes in a DataGrid

Let’s say you want to add checkboxes into a column of a DataGrid, but you don’t want to add it to every row. You want to make whether or not the checkbox appears, conditional on data in that row. In this sample, what we’re going to check for, is whether the name of the author STARTS with “M”. If it does NOT start with “M”, then we’ll add a checkbox. If it does start with “M”, we will NOT add a checkbox. To do this, we use the OnItemDataBound Event of the DataGrid, and create a Sub called ‘CheckData’ to look at the data and make the checkboxes visible or not.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" Runat="server">
Dim ordList as String=""
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=Pubs"
Dim MySQL as string = "Select Top 10 au_id, au_fname + '' '' + au_lname " & _
"as FullName from Authors"
Dim MyConn as New SQLConnection(strConn)
Dim ds as DataSet=New DataSet()
Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
Cmd.Fill(ds,"PBAuthors")
dgPublishers.Datasource=ds.Tables("PBAuthors").DefaultView
dgPublishers.DataBind()
end if
End Sub

Sub CheckData(sender As Object, e As DataGridItemEventArgs)
Dim sName as String
if e.Item.ItemType.ToString="Item" or e.Item.ItemType.ToString="AlternatingItem"
sName=e.Item.Cells(2).text
Dim chkExp as CheckBox= e.Item.FindControl("ck1")
if Not sName.StartsWith("M") then
chkExp.Visible="True"
else
chkExp.Visible="False"
End If
End If
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 4.0">
<title>Using Conditional Checkboxes with a DataGrid</title>
</head>
<body>
<form id="form1" Runat="server">
<div align="center">
<asp:Label ID="label1" ForeColor="Blue" Font-Bold="True" Runat="server" />
<asp:Datagrid Runat="server"
Id="dgPublishers"
GridLines="Both"
cellpadding="0"
cellspacing="0"
Headerstyle-BackColor="#BDCFE7"
Headerstyle-Font-Name="Arial"
Headerstyle-Font-Size="8"
BackColor="#E7EFFF"
Font-Name="Arial"
Font-Size="8"
BorderColor="Black"
AutogenerateColumns="False"
OnItemDataBound="CheckData">
<Columns>
<asp:TemplateColumn HeaderText="Select">
<ItemTemplate>
<asp:Checkbox id="ck1" Runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="au_id" HeaderText="Author ID">
</asp:BoundColumn>
<asp:BoundColumn DataField="FullName" HeaderText="Author Name">
</asp:BoundColumn>
</Columns>
</asp:DataGrid>

</div>
</form>
</body>
</html>

Using Checkboxes with DataGrids

One of the most request scenarios, using a DataGrid, in ASP.Net is how to use Checkboxes with a DataGrid, and how to iterate through that selection, and get information about the checked item.

This sample shows how to check all items, un-check all items, and how to select several items, and return information from the DataGrid, based on each item checked. Notice here, that we’re using the FindControl metod to locate the Checkboxes – and check to see if each
Checkbox is Checked (cb.Checked), in order to accomplish this scenario.

One last thing – check out the ‘Kill Ending’ function. Since we’re creating a list, we are adding a comma after every checked item found. Therefore, at the end of the string we’re building, there will be an extra comma. This function removes that comma at the end of the string.
Here, we use the Authors table in the Pubs database, using SQL Server.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" Runat="server">
Dim ordList as String=""
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
		Dim strConn as string = "server=YourServer;uid=yourUID;pwd=yourPWD;database=Authors"
		Dim MySQL as string = "Select Top 10 au_id, au_fname + '' '' + au_lname " & _
			"as FullName from Authors"
		Dim MyConn as New SQLConnection(strConn)
		Dim ds as DataSet=New DataSet()
		Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
		Cmd.Fill(ds,"PBAuthors")
		dgPublishers.Datasource=ds.Tables("PBAuthors").DefaultView
		dgPublishers.DataBind()
end if
End Sub
Sub doSelectAll(Source as Object, E as EventArgs)
        Dim dgItem As DataGridItem
        Dim chkDGrid As System.Web.UI.WebControls.CheckBox
            For Each dgItem In dgPublishers.Items
                chkDGrid = dgItem.FindControl("chk1")
                chkDGrid.Checked = "True"
            Next
End Sub

Sub doClearAll(Source as Object, E as EventArgs)
        Dim dgItem As DataGridItem
        Dim chkDGrid As System.Web.UI.WebControls.CheckBox
            For Each dgItem In dgPublishers.Items
                chkDGrid = dgItem.FindControl("chk1")
                chkDGrid.Checked = "False"
            Next
            label1.text=""
End Sub

Sub GetAuthorIDs(Source as Object, E as EventArgs)
Dim i As Integer
For i = 0 To dgPublishers.Items.Count - 1
   Dim dgItem As DataGridItem = dgPublishers.Items(i)
   Dim cb As CheckBox = CType(dgItem.FindControl("chk1"), CheckBox)
   If Not (cb Is Nothing) And cb.Checked Then
   	ordList+=dgItem.Cells(1).Text & ","
   End If
Next i
label1.text=KillEnding(Trim(ordList))
End Sub

Function KillEnding(sItem as String)
	Return sItem.Substring(0,sItem.Length-1)
End Function
</script>
<html>
	<head>
		<meta name="GENERATOR" Content="ASP Express 4.0">
		<title>Using Checkboxes with a DataGrid</title>
	<STYLE TYPE="text/css">
<!--
BODY {
	font-family : Verdana;
	font-size : 11pt;
}
-->
</STYLE>
</head>
	<body>
		<form id="form1" Runat="server">
			<div align="center">
			<asp:Label ID="label1" ForeColor="Blue" Font-Bold="True" Runat="server" />
				<asp:Datagrid Runat="server"
					Id="dgPublishers"
					GridLines="Both"
					cellpadding="0"
					cellspacing="0"
					Headerstyle-BackColor="#BDCFE7"
					Headerstyle-Font-Name="Arial"
					Headerstyle-Font-Size="8"
					BackColor="#E7EFFF"
					Font-Name="Arial"
					Font-Size="8"
					BorderColor="Black"
					AutogenerateColumns="False">
					<Columns>
						<asp:TemplateColumn HeaderText="Select">
							<ItemTemplate>
								<asp:Checkbox id="chk1" Runat="server" />
							</ItemTemplate>
						</asp:TemplateColumn>
						<asp:BoundColumn DataField="au_id" HeaderText="Author ID">
						</asp:BoundColumn>
						<asp:BoundColumn DataField="FullName" HeaderText="Author Name">
						</asp:BoundColumn>
					</Columns>
				</asp:DataGrid>
				<asp:Button id="btnSelectAll"
					Text="Select All" onclick="doSelectAll" Runat="server" />
				<asp:Button id="btnClearAll"
					Text="Clear All" onclick="doClearAll" Runat="server" />&nbsp;
				<asp:Button id="btnAuthorIDs"
					Text="Get Author IDs" onclick="GetAuthorIDs" Runat="server" />
			</div>
		</form>
	</body>
</html>

DataGrid Tips and Tricks

Here, you’ll see one of the more complicated code samples on this site. Here, you’ll see how to:

  1. Use ReadyOnly BoundColumns with a DataGrid
  2. Use a DropDownList in an Editable DataGrid
  3. Control the size of a TextBox in an Editable DataGrid
  4. Use the DataKeyField property of the DataGrid

We’ll also show how to, in the DropDownLists, select the correct item, based on the data retrieved from the database.

For the DropDownList and the controled TextBox size, we use a TemplateColumn, inside of which we assign an ItemTemplate (for data when not in Edit Mode), and an EditItemTemplate.

As you will see, in the ReadOnly Bouncdolumn, when the DataGrid goes into Edit Mode, a TextBox is NOT created, since we don’t want this data editable. As you’ll most likely notice, it’s also not referenced in the SQL statement for that same fact.

By assigning the DataKeyField property in the DataGrid, we are able to reference the exact record, when updating the table by using:
dgCust.DataKeys(e.Item.ItemIndex)) in the ID parameter.