Getting ID Inside a Gridview

There are two common ways to get the ‘id’ associated with a particular GridView. One is to actually retrieve it, with the ID field being visible in the Gridview. But one way is to make a label INVISIBLE, and bind it to the ID field of the data.

This code sample uses and shows both. Notice that the SelectCommand for the DataSourceID are in the Page_Load event. This is to cut down on page real estate, due to the size of the SQL statement.

The ‘Get’ column retrieves the ID from the visible column in the datagrid (the label in the TemplateField, bound to the ID). The ‘Other’ column retrieves the ID from the label inside the first column that has it’s Visible property set to ‘false’.

<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
SQLDS1.SelectCommand="SELECT Products.ProductID, Products.ProductName, Categories.CategoryID," & _
"Categories.CategoryName, Suppliers.CompanyName FROM Products INNER JOIN Categories ON " & _
"Products.CategoryID = Categories.CategoryID INNER JOIN Suppliers ON " & _
"Products.SupplierID = Suppliers.SupplierID"
End Sub
Sub ImageButton1_Click(sender As Object, e As System.Web.UI.ImageClickEventArgs)
Dim gvr As GridViewRow
gvr = CType(sender.parent.parent, GridViewRow)
Dim lbl As Label = CType(gvr.FindControl("lblID"), Label)
lblResults.Text = lbl.Text
End Sub
Sub IB_Hidden(sender As Object, e As System.Web.UI.ImageClickEventArgs)
Dim gvr As GridViewRow
gvr = CType(sender.parent.parent, GridViewRow)
Dim lbl2 As Label = CType(gvr.FindControl("lblOther"), Label)
lblResults.Text = lbl2.Text & "/Other"
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 5.0">
<title>Getting An ID of a GridViewRow</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:GridView Runat="server"
Id="MyGridView"
GridLines="Both"
cellpadding="0"
cellspacing="0"
BorderWidth="1"
AutoGenerateColumns="False"
Headerstyle-BackColor="#BDCFE7"
Headerstyle-Forecolor="#000000"
Headerstyle-Font-Names="Arial"
Headerstyle-Font-Bold="True"
Headerstyle-Font-Size="10"
BackColor="#E7EFFF"
Font-Names="Arial"
Font-Size="8"
AlternatingRowStyle-BackColor="#FBFBFB"
AlternatingRowStyle-Font-Names="Arial"
AlternatingRowStyle-Font-Size="8"
BorderColor="Black"
AllowSorting = "True"
AllowPaging = "True"
PageSize = "10"
PagerSettings-Mode = "Numeric"
DataSourceID="SQLDS1">
<Columns>
<asp:TemplateField HeaderText="ProductID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text=''<%# Bind("ProductID") %>''></asp:Label>
<asp:Label ID="lblOther" Visible="False" runat="server" Text=''<%# Bind("ProductID") %>''></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
<asp:TemplateField HeaderText="Get">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="images/update.gif"
OnClick="ImageButton1_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Other">
<ItemTemplate>
<asp:ImageButton ID="ibHidden" runat="server" ImageUrl="images/update.gif"
OnClick="IB_Hidden" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblResults" Font-Bold="True" Font-Size="14pt" Runat="server" />
<asp:SqlDataSource ID="SQLDS1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>">
</asp:SqlDataSource>
</form>
</body>
</html>

CheckboxList Inside a DetailsView

This sample shows how to use a CheckBoxList inside a DetailsView. Here, we’re, of course, using the Northwind Database, with the CheckboxList binding to the Categories table, and then, when a selection is made from the GridView, the DetailsView will show the full Product, and the CheckBoxList will have the correct category selected automatically.

<%@ Page Language="VB" %>
<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
SqlDataSource2.SelectCommand="SELECT Products.ProductID, Products.ProductName, Categories.CategoryID, " & _
"Categories.CategoryName, Suppliers.CompanyName FROM Products INNER JOIN Categories ON " & _
"Products.CategoryID = Categories.CategoryID INNER JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID"
SqlDataSource3.SelectCommand="SELECT Products.ProductID, Products.ProductName, Categories.CategoryID," & _
"Categories.CategoryName, Suppliers.CompanyName, Products.QuantityPerUnit, Products.UnitPrice, " & _
"Products.UnitsInStock, Products.UnitsOnOrder FROM Products INNER JOIN Categories ON Products.CategoryID = " & _
"Categories.CategoryID INNER JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID " & _
"WHERE (Products.ProductID = @ProductID)"
End Sub
</script>
<html>
<head runat="server">
<meta name="GENERATOR" Content="ASP Express 5.0">
<title>Master Detail - CheckboxList</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table border="1"><tr>
<td valign="top">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"
DataSourceID="SqlDataSource2" AllowPaging="True">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="ProductID" HeaderText="ProductID" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
</Columns>
</asp:GridView></td>
<td valign="top">
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="ProductID"
DataSourceID="SqlDataSource3" Height="50px">
<Fields>
<asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:TemplateField HeaderText="CategoryName" SortExpression="CategoryName">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CategoryName") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CategoryName") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:CheckBoxList ID="CheckBoxList1" runat="server" DataSourceID="sqlCats" DataTextField="CategoryName"
DataValueField="CategoryID" SelectedValue='<%# Bind("CategoryID") %>'>
</asp:CheckBoxList><asp:SqlDataSource ID="sqlCats" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT CategoryID, CategoryName FROM Categories"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
<asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" SortExpression="QuantityPerUnit" />
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
<asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder" SortExpression="UnitsOnOrder" />
</Fields>
</asp:DetailsView></td>
</tr>
</table>

<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>">
<SelectParameters>
<asp:ControlParameter ControlID="GridView1"
Name="ProductID" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>

<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>">
</asp:SqlDataSource>
</div>
</form>
</body>
</html>

DetailsView w/DDL – Master/Detail

This sample adds on to one of our other Master Detail code samples. What we’ve added here, is a DropDownList inside a DetailsView, for Editing purposes. You can easily see how the SelectedValue of the DropDownlist (when entering Edit mode) keeps the same state as the record.

<script language="VB" Runat="server">
Dim strUpdate as String
Dim strSelect as String
Sub Page_Load(Source as Object, E as EventArgs)
strSelect="SELECT [au_id], [au_lname], [au_fname], [phone], " & _
"[address], [city], [state], [zip], [contract] FROM [authors] " & _
"WHERE ([au_id] = @au_id)"
strUpdate="UPDATE [authors] SET [au_lname]=@au_lname, " & _
"[au_fname]=@au_fname, [phone]=@phone, [address]=@address, " & _
"[city]=@city, [state]=@state, [zip]=@zip, [contract]=@contract " & _
"WHERE [au_id]=@au_id"
SQLDS3.SelectCommand=strSelect
SQLDS3.UpdateCommand=strUpdate
End Sub

Sub DVAfterUpdate(sender As Object, e As DetailsViewUpdatedEventArgs)
gvAuthors.DataBind()
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 4.5">
<title>
Master/Detail Editing with DetailsView
</title>
</head>
<body>
<form id="form1" Runat="server">
<table>
<tr>
<td align="Center" valign="Top">
<asp:GridView Runat="server"
Id="gvAuthors"
GridLines="Both"
cellpadding="0"
cellspacing="0"
Headerstyle-BackColor="#BDCFE7"
Headerstyle-Font-Name="Arial"
Headerstyle-Font-Size="12"
BackColor="#E7EFFF"
Font-Name="Arial"
Font-Size="10"
BorderColor="Black"
DataSourceID="SQLDS2"
DataKeyNames="au_id"
AllowPaging="True"
AllowSorting="True"
AutoGenerateColumns="False">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="au_id" HeaderText="ID" ReadOnly="True" />
<asp:BoundField DataField="au_lname" HeaderText="LName" />
<asp:BoundField DataField="au_fname" HeaderText="Fname"  />
<asp:BoundField DataField="state" HeaderText="State" />
</Columns>
</asp:GridView>
</td>
<td align="Left" valign="Top">
<asp:DetailsView
DataKeyNames="au_id" DataSourceID="SQLDS3"
GridLines="Both"
cellpadding="0"
cellspacing="0"
Headerstyle-BackColor="#BDCFE7"
Headerstyle-Font-Name="Arial"
Headerstyle-Font-Size="12"
BackColor="#E7EFFF"
Font-Name="Arial"
Font-Size="10"
BorderColor="Black"
HeaderText="Author Details" AutoGenerateRows="False"
HeaderStyle-Font-Bold="True"
OnItemUpdated="DVAfterUpdate"
ID="dvPubs" runat="server">
<Fields>
<asp:BoundField DataField="au_id" HeaderText="ID" ReadOnly="True"  />
<asp:BoundField DataField="au_lname" HeaderText="Lname"  />
<asp:BoundField DataField="au_fname" HeaderText="Fname"  />
<asp:BoundField DataField="phone" HeaderText="Phone"  />
<asp:BoundField DataField="address" HeaderText="Address"  />
<asp:BoundField DataField="city" HeaderText="City"  />
<asp:TemplateField HeaderText="State">
<ItemTemplate>
<asp:Label id="label1" runat="server"
Text=''<%# Container.DataItem("State") %>''>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList id="ddlStates" runat="server"
DataSourceID="dsStates"
BackColor="Pink"
DataTextField="StAbbr" DataValueField="StAbbr"
SelectedValue=''<%# Bind("State") %>''>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="zip" HeaderText="Zip"  />
<asp:CheckBoxField DataField="contract" HeaderText="Contract"  />
<asp:CommandField ShowEditButton="True" />
</Fields>
</asp:DetailsView>
</td>
</tr>
</table>
<asp:SqlDataSource ID="SQLDS2" runat="server"
SelectCommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors]"
ConnectionString="<%$ ConnectionStrings:Pubs %>">
</asp:SqlDataSource>
<asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:Pubs %>" ID="SQLDS3"
runat="server"
SelectCommand="SELECT [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors] WHERE ([au_id] = @au_id)">
<SelectParameters>
<asp:ControlParameter ControlID="gvAuthors" Name="au_id"
PropertyName="SelectedValue"
Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SQLDataSource ID="dsStates"
Runat="Server"
SelectCommand = "SELECT STabbr From states"
DataSourceMode="DataSet"
ConnectionString="<%$ ConnectionStrings:StatesDB20 %>">
</asp:SQLDataSource>
</form>
</body>
</html>

Conditional GridView Row Coloring By Date

This is another code sample demonstrating conditional row coloring with a Gridview. However, this one is based on the date in one of the columns. First, in the Date column we’re using, we cast the raw text to a date, and then, to compare the date, notice how we use a Select Case statement. And, of course this is all done inside a procedure which is assigned to the ‘OnRowDataBound’ event of the GridView.

<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
DS1.SelectCommand="SELECT Orders.OrderID, Customers.CompanyName, " & _
"Customers.ContactName, Orders.ShippedDate FROM Orders INNER JOIN " & _
"Customers ON Orders.CustomerID = Customers.CustomerID " & _
"WHERE (Orders.CustomerID = ''AROUT'')"
End Sub
Sub doColor(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim sDate as DateTime
sDate=cDate(e.Row.Cells(3).Text)
Select Case sDate
Case is >"3/1/1998"
e.Row.BackColor = Drawing.Color.Beige
Case is  > "1/1/1998"
e.Row.BackColor = Drawing.Color.Lavender
Case "1/1/1997" to "1/1/1998"
e.Row.BackColor = Drawing.Color.MintCream
Case "1/1/996" to "1/1/1997"
e.Row.BackColor = Drawing.Color.MistyRose
End Select
End If
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 5.0">
<title>Conditional GridView Coloring By Date</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:GridView Runat="server"
Id="MyGridView"
GridLines="Both"
Border-Width="1"
cellpadding="2"
cellspacing="0"
Headerstyle-BackColor="#7988B7"
Headerstyle-Forecolor="#FFFFFF"
Headerstyle-Font-Names="Arial"
Headerstyle-Font-Size="12"
Font-Names="Arial"
Font-Size="8"
OnRowDataBound="doColor"
BorderColor="Black"
DataSourceID="DS1"
AutogenerateColumns="False">
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="OrderID"></asp:BoundField>
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName"></asp:BoundField>
<asp:BoundField DataField="ContactName" HeaderText="ContactName"></asp:BoundField>
<asp:BoundField DataField="ShippedDate" DataFormatString="{0:MM/dd/yyyy}" HtmlEncode="false" HeaderText="ShippedDate"></asp:BoundField>
</Columns>
</asp:GridView>

<asp:SQLDataSource ID="DS1"
Runat="Server"
ConnectionString="server=(local);Database=Northwind;pwd=YourPWD;uid=sa;">
</asp:SQLDataSource>
</form>
</body>
</html>

Using a Panel for a Scrollable GridView in ASP.NET

Most previous examples of scrolling with a DataGrid used a DIV tag. Now, with the Panel control’s ‘Scrollbars’ property, you can choose vertical, horizontal, or both – or even ‘Auto’. Of course, the html rendered is a DIV tag, but using an ASP.Net control to do it makes it a little easier to remember than using a style tag, inside a ‘div’ with ‘overflow’ as an attribute, and setting it to ‘scroll’.

<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
ds1.SelectCommand = "SELECT Products.ProductID, " & _
"Products.ProductName, Products.SupplierID, Products.CategoryID," & _
"Categories.CategoryName, Suppliers.ContactName FROM Products " & _
"INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID " & _
"INNER JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID"
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 5.0">
<title>Scrollable GridView</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:Panel ID="Panel1" ScrollBars="Vertical" BorderStyle="Inset" BorderWidth="1px"
BorderColor="Black" runat="server" Height="142px" Width="350px">
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="ds1">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ProductID"
InsertVisible="False"
ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName"
SortExpression="ProductName" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName"
SortExpression="CategoryName" />
<asp:BoundField DataField="ContactName" HeaderText="ContactName"
SortExpression="ContactName" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="ds1" runat="server"
ConnectionString="<%$ ConnectionStrings:YourNWConnectionString %>">
</asp:SqlDataSource>
</asp:Panel>
</form>
</body>
</html>

Inserting a DataSet into Cache

Sometimes, we don’t want to hit the database every time we display data, especially when the database doesn’t really change that much. Therefore, to be able to handle this, whenever the page hits the database and creates a DataSet the first time, it can be inserted into Cache, using the Cache API directly.

Create a new page, and call it ‘CacheTest.aspx’. Copy the code below into that page. Notice, that there is a button on the page, below the GridView. What it does, is remove the Cache that had data Inserted into it. That way, you can see that it goes back to read the data directly from the Database, once the Cache is removed. You will see in the text of the label at the bottom of the GridView, just exactly where the page is getting its data (from either the Cache, or directly from the Database).

<%@ Page Language="VB" Trace="True" TraceMode="SortByCategory" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" Runat="server">
Dim strConn as String
Dim MyConn as SQLConnection
Dim MySQL as String
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
strConn=ConfigurationManager.ConnectionStrings("YourConnString").ConnectionString
MySQL = "Select [EmployeeID], [FirstName], [LastName], [Title], [BirthDate], [email] " & _
"from NWEmployees"
MyConn = New SQLConnection(strConn)
Dim ds as DataSet
ds=CType(Cache("Employees"), DataSet)
if ds Is Nothing then
ds=New DataSet()
Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
Cmd.Fill(ds,"Employees")
Cache.Insert("Employees", ds)
lblCache.text="Reading data Directly"
else
lblCache.text="Reading data from Cache"
End If
gvEmp.Datasource=ds
gvEmp.DataBind()
End If
End Sub

Sub RemoveCache(Source as Object, E as EventArgs)
Cache.Remove("Employees")
response.Redirect("CacheTest.aspx")
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 5.0">
<title>Inserting a DataSet into Cache</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:GridView Runat="server"
Id="gvEmp"
GridLines="Both"
Border-Width="1"
cellpadding="2"
cellspacing="0"
Headerstyle-BackColor="#7988B7"
Headerstyle-Forecolor="#FFFFFF"
Headerstyle-Font-Names="Arial"
Headerstyle-Font-Bold="True"
Headerstyle-Font-Size="12"
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">
</asp:GridView>
<asp:Label ID="lblCache" ForeColor="Red" Font-Bold="True" Runat="server" /><br />
<asp:Button id="btnCache" Text="Remove Cache"
onclick="RemoveCache" Runat="server" />
</form>
</body>
</html>

Using MySQL with v2.0 – DataSource Ctrl

This sample shows how to use the SQLDataSource control (yes – SQL!), to connect to a MySQL database. This can, by the way, be done with no code at all, by assigning the ConnectionsString in the SQLDataSource control itself. However, to preserve horizontal screen real estate, by using multiple lines to define the connectionstring, this sampple is done, assigning the connectionstring in the Page_Load event.

Note, that, to accomplish this, we use ‘System.Data.Odbc’ as the ProviderName in the SQLDataSource control

<%@ Page Language="VB" %>
<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
DS1.ConnectionString="Driver={MySQL ODBC 3.51 Driver};server=YourServerIP;database=" & _
"YourDB;user=YourUID;pwd=YourPWD;option=3;"
End Sub
</script>
<html>
<head runat="server">
<title>Using MySQL with ASP.Net V2.0</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="DS1" runat="server"
ProviderName="System.Data.Odbc"
SelectCommand="Select CategoryID, CategoryName, Description from Categories order by categoryID desc">
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="#E6E6FA" AlternatingRowStyle-BackColor="#F0F0F0"
BorderStyle="Ridge" BorderWidth="1px" CellPadding="1" CellSpacing="1"
HeaderStyle-BackColor="#4747D8" HeaderStyle-Font-Bold="True" HeaderStyle-ForeColor="#E7E7FF"
DataKeyNames="CategoryID" DataSourceID="DS1" GridLines="None">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID"
ReadOnly="True" SortExpression="CategoryID" />
<asp:BoundField DataField="CategoryName"
HeaderText="CategoryName" SortExpression="CategoryName" />
<asp:BoundField DataField="Description"
HeaderText="Description" SortExpression="Description" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>

Screen Scraping with VB.Net

This code sample is written in VB.Net, showing how to ‘screen scrape a web page from another server.

It’s based on a page at ASP Alliance, created by Steve Smith, showing the same thing, done in C#. To see the C# version, go to: http://authors.aspalliance.com/stevesmith/articles/netscrape.asp.

<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>
<script language="VB" runat="server">
   	Sub Page_Load(Source as Object, E as EventArgs)
		myPage.text=readHTMLPage("http://aspnet101.com")
	End Sub
Function readHTMLPage(url as String) as String
	Dim result as String
	Dim objResponse as WebResponse
	Dim objRequest as WebRequest=System.Net.HTTpWebRequest.Create(url)
	Dim sr as StreamReader
	objResponse=objRequest.GetResponse()
	sr=new StreamReader(objResponse.GetResponseStream())
	result=sr.ReadToEnd()
	sr.Close
	return result
End Function
</script>
<html>
<body>
<b>This content is being populated from a separate HTTP request to
<a href="http://aspnet101.com/">http://aspnet101.com</a>:</b><br />
(based on a C# example of the same functionality at :<br>
<a href="http:aspalliance.com/stevesmith">http:aspalliance.com/stevesmith</a>,
done by Steve Smith)<hr/>
<asp:literal id="myPage" runat="server"/>
</body>
</html>

Sorting Visually with a GridView

Yes, sorting is a piece of cake, with a Gridview, using ASP.Net v2.0. However, some have asked how to add an image, to visually display which column is being sorted, and which direction the sort is. Therefore, this code sample was born.

First, what we need to do is to create a sub (AddSortImage) to dynamically add an image to the correct column, pointing the correct direction, like an arrow. In this sub, we

GridView – Conditional Row Coloring

This sample shows how easy it is, with ASP.net v2.0, to use conditional Row Coloring with a GridView

<script language="VB" Runat="server">
	Sub Page_Load(Source as Object, E as EventArgs)
		DS1.SelectCommand="SELECT TOP 40 " & _
		"Categories.CategoryName, Products.ProductName, Products.UnitsInStock " & _
		"From Categories INNER JOIN Products ON Products.CategoryID=Categories.CategoryID" & _
		" Order BY Categories.CategoryID"
	End Sub

Sub doColor(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
   Select Case e.Row.Cells(0).Text
	Case  "Beverages"
         	e.Row.BackColor = Drawing.Color.Lavender
	Case "Condiments"
		if e.row.Cells(1).text.SubString(0,1)="G" then
         		e.Row.BackColor = Drawing.Color.Beige
         	else
         		e.Row.BackColor = Drawing.Color.MintCream
         	End If
	Case "Confections"
           	e.Row.BackColor = Drawing.Color.MistyRose
	Case "Dairy Products"
		e.Row.BackColor = Drawing.Color.MediumSpringGreen
   End Select
End If
End Sub
</script>
<html>
	<head>
		<meta name="GENERATOR" Content="ASP Express 5.0">
		<title>GridView - Conditional Row Coloring</title>
	</head>
	<body>
		<form id="form1" Runat="server">
			<asp:GridView Runat="server"
				Id="MyGridView"
				GridLines="None"
				cellpadding="0"
				cellspacing="0"
				Headerstyle-BackColor="#6397F8"
				Headerstyle-Forecolor="#000000"
				Headerstyle-Font-Names="Arial"
				Headerstyle-Font-Bold="True"
				Headerstyle-Font-Size="12"
				Font-Names="Arial"
				Font-Size="10"
				BorderColor="Black"
				AllowSorting = "True"
				OnRowDataBound="doColor"
				DataSourceID="DS1">
			</asp:GridView>
			<asp:SQLDataSource ID="DS1"
				 Runat="Server"
				ConnectionString="YourConnStringGoesHere">
			</asp:SQLDataSource>
		</form>
	</body>
</html>