Home

ASP.net 2.0 Unleashed [Walther] stuffs [Assumes reader already knows how to program in .net, including classes, inheritance, methods, properties, events, event handlers etc]

All of these examples are based on Walther's 1800 page ASP Unleashed 2.0 book. The book covers just about everything, and I recommend going through it as I have done, and repeating all of the exercises without opening the accompanying CD and copying/pasting anything.  Repeat exercises with any significant change from the previous one: this ends up being most of them because Stephen doesn't waste the reader's time with pointless/redundant examples. I have mixed and matched as I saw fit, making sure that I am familiar with each control/lesson.

I am using framework 1.1, so some of the exercises I didn't complete this time through because 1.1 doesn't support them (like Generic Lists), but I still read them over and make sure I understand them. The primary point here is to make sure I have a good idea about what all of these controls/objects/libraries do so that I can quickly program a solution to a given problem without fumbling around for the right control--or in the worst case--creating something from scratch when there's already a control that does what you want.

Most of this stuff is database driven of course. Understanding Databases and SQL is essential at this point in the technologies, so I (and neither does he) am not going to spend time explaining SQL joins/clauses/tables/keys etc.  As usual, Wikipedia is a good place to start->Structured Query Language

 

Downloading and using SQL server express is recommended over using only MS Access because in the long run, you'll end up using SQL server or some other enterprise scalable application rather than Access, and it's best to have some experience in the environment. I don't use a visual query builder since the only thing I've had available since 2000 at work is the simple Query Analyzer for SQL server,  which amounts to a text-only interface for typing queries and build scripts. All my queries are written by hand, although for Peoplesoft (which has a very complex underlying database structure), one can use a query builder and copy the SQL and then paste that into Query analyzer in some cases, but their builder has some drawbacks like forced row level security enforced via inner joins on security tables that makes doing outer joins impossible and also slows down the return of large datasets.

 

Step1 should be: Download  and install SQL server express

Step2: Create a simple table and load a few rows

Create a new database called "MyDatabase" for example

 

Create a new table with Movie as a key

USE MyDatabase

Insert into dbo.Movies values ('What about Bob','Frank Oz','B Williams')

 

Insert some data

USE MyDatabase

select * from dbo.Movies

 

 

Select some data

Top

Started 12/24/2007

Last Updated: []

AJAX (Asynchronous Javascript and XML) -method of performing server-side transactions without submitting the entire page

Ordinarily, in order to make contact with the server, the user 'submits' the page contents, but you may not want to submit the entire form just to see if the UserName ( or EMPLID in this case) is taken already. AJAX comes in handy by allowing the page to make the request for one field (or a set number of fields) and send only their contents to the server for operations like a select count(*) to be carried out to see if the UserName or EMPLID is in the database already. This is what this example does.

For this particular set of pages, a simple Access database (although using SQL server express is much easier if you just need a database) is required, and this set uses a simple table with the following features

A simple table indexed by EMPLID

Source (.zip)

Top


Uploading binary data (OLEObject in Access) to a database and using a Filehandler to display it.

 

User can browser for a file (in this cast, a txt file)

When the user submits, the datafile is uploaded to an Access table capable of storing binary data.

Clicking the links shown will send the datastream to their browser, thereby allowing the programmer to store submitted data in a database.

An Access table with the following properties is needed for this

Two files are needed, shown below

Filehandler.ashx UploadsDB.aspx

<%@ WebHandler Language="VB" Class="FileHandler" %>

Imports System

Imports System.Web

Imports system.Data

Imports System.Data.OleDb

 

Public Class FileHandler : Implements IHttpHandler

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

Dim conn As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;data source=" & context.Server.MapPath("~/people.mdb")

context.Response.ContentType = "text/plain"

Dim con As OleDbConnection = New OleDbConnection(conn)

Dim cmd As OleDbCommand = New OleDbCommand("Select FileBytes from DataTable where FileName = @FileName", con)

cmd.Parameters.AddWithValue("@FileName", context.Request("FileName"))

con.Open()

Dim file() As Byte = CType(cmd.ExecuteScalar, Byte())

context.Response.BinaryWrite(file)

End Sub

Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable

Get

Return False

End Get

End Property

End Class

 

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Protected Sub Submit_Click(ByVal sender As Object, ByVal e As System.EventArgs)

If myuploader.HasFile Then

myAccessDB.Insert()

End If

End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>File Upload Database</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:FileUpload ID="myuploader" runat="server" />

<asp:AccessDataSource ID="myAccessDB" runat="server"

DataFile="~/people.mdb"

SelectCommand="Select FileName,FileBytes from DataTable"

InsertCommand="Insert Into DataTable (FileName,FileBytes) VALUES (@FileName,@FileBytes)"

>

<InsertParameters>

<asp:ControlParameter Name="FileName" ControlID="myuploader" PropertyName="FileName" />

<asp:ControlParameter Name="FileBytes" ControlID = "myuploader" PropertyName="FileBytes" />

</InsertParameters>

</asp:AccessDataSource>

<br />

<asp:Button ID="Submit" runat="server" OnClick="Submit_Click" Text="Submit" /><br />

<br />

<br />

<br />

<br />

<asp:Repeater ID="rptfiles" runat="server"

DataSourceID = "myAccessDB">

<HeaderTemplate>

<ul class="fileList">

</HeaderTemplate>

<ItemTemplate>

<li>

<asp:HyperLink ID="lnkfile" Text='<%#eval("FileName") %>' NavigateUrl='<%#eval("FileName","~/FileHandler.ashx?FileName={0}") %>' runat="server" />

</li>

</ItemTemplate>

</asp:Repeater>

</div>

</form>

</body>

</html>

 

Top


Kurt Bingham 12/25/2007

Databinding using SQL server express (two list types)

Bulleted List

  • Jaws
  • Star Wars
  • Lord of the Rings
  • What about Bob

CheckBox List

Page as it is displayed

<%@ Page Language="VB" AutoEventWireup="false"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id="Head1" runat="server">

<title>DataLists</title>

</head>

<body>

<form id="form1" runat="server">

<asp:BulletedList ID="BulletedList1" DataSourceID="SqlDataSource1" DataTextField="Movie" runat="server" />

<asp:CheckBoxList ID="CheckboxList1" DataSourceID="Sqldatasource1" datatextfield="Director" runat="server" />

<div>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=DLAHD25V11\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True"

ProviderName="System.Data.SqlClient" SelectCommand="Select Movie,Director from Movies"></asp:SqlDataSource>

</div>

</form>

</body>

</html>

 

 

Simply create a new datasource. The previous examples above use Access, which is its own datasource type[asp:AccessDataSource]--but in this case, we're using SQL express on this machine, a trusted connection directly to the database[asp:SqlDataSource] . There is no file reference as there is with access. You can generate this information by using the visual builder.

 

Also notice a "Select Command" is used. Those columns are references in the checkboxlist and bulletedlist above.

 

 

 

Kurt Bingham 12/26/2007

Top


Tabular Data Binding

Tabular data is simply the dataset as a non-relational dataset displayed in grid or repeat or a details view as seen below. 

 

Movie Director Producer
Jaws Spielberg Dir Spielberg Prod
Star Wars Lucas Dir Lucas Prod
Lord of the Rings Jackson Dir Jackson Prod
What about Bob Frank Oz B Williams


Datalist

Jaws directed by Spielberg Dir Lord of the Rings directed by Jackson Dir
Star Wars directed by Lucas Dir What about Bob directed by Frank Oz

 

Repeater

Jaws produced by Spielberg Prod Star Wars produced by Lucas Prod Lord of the Rings produced by Jackson Prod What about Bob produced by B Williams


Details View

Movie Lord of the Rings
Director Jackson Dir
Producer Jackson Prod
1 2 3 4
The Page as it is displayed in the browser

 

 

 

Several different ways of displaying data shown to the left, all using the same datasource.

 

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Tabular Data</title>

<style type="text/css" >

.floater

{float:left;

border:solid 1px blue;

padding:3px;

margin:5px;

}

</style>

</head>

<body>

<form id="form1" runat="server">

<asp:SqlDataSource ID="srcMovies" runat="server" ConnectionString="Data Source=DLAXXXX\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True"

SelectCommand="select Movie,Director,Producer from dbo.Movies"></asp:SqlDataSource>

<asp:GridView ID="GridView1" DataSourceID="srcMovies" runat="server" />

<br />

<div class="floater">

<h3>Datalist</h3>

<asp:DataList ID="DataList1" DataSourceID="srcMovies" RepeatColumns="2" runat="server">

<ItemTemplate><%#Eval("Movie") %><i>&nbsp;directed by&nbsp;</i><%#Eval("Director") %> </ItemTemplate>

</asp:DataList>

</div>

<br />

<div class="floater">

<h3>Repeater</h3>

<asp:Repeater ID="repeater1" DataSourceID="srcMovies" runat="server">

<ItemTemplate>

<%#eval("Movie") %><i>&nbsp;produced by&nbsp;</i><%#eval("Producer") %>

</ItemTemplate>

</asp:Repeater>

</div>

<br />

<div class="floater">

<h3>Details View</h3>

<asp:DetailsView ID="DetailsView1" DataSourceID="srcMovies" AllowPaging="true" runat="server" />

</div>

</form>

</body>

</html>

 

Define a simple DIV format for the data called floater--basically to put a box around each data area. Once the data is bound to the control, the controls basically takes care of the rest of the display. Of course, any events or actions would be programmed later

 

 

 

 

 

 

Define the datasource based on our SQL server express database on the local machine

Create a 'Select Command' in order to return a dataset, in this case, it returns the Movie, Director, and Producer from the table in a list. These columns are referenced directly in the objects below.

 

The Gridview

 

 

The DataList

 

 

 

 

 

The Repeater

 

 

 

 

 

 

The DetailsView

 

Top


Kurt Bingham 12/27/2007

Hierarchical Data (XML)

 

 


First, Create a simple XML file like this given below (mydata.xml)

<?xml version="1.0" encoding="utf-8" ?>

<scientists>

<CS>

<MarvinMinsky/>

<JohnMcarthy/>

</CS>

<AstroPhysics>

<CarlSagan/>

<StephenHawking/>

</AstroPhysics>

<Biology>

<FrancisCrick/>

<RichardDawkins/>

</Biology>

</scientists>

 

XML is basically a method of storing relational data in files. Here I am defining different types of scientists within their respective fields all within the 'scientists' root.

 

Scientist->CS->MarvinMinsky etc.

The ASPX page code

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Hierarchical Data /XML</title>

<style type="text/css" >

.mybox

{float:left;

width:30%;

border:solid 1px red;

padding:10px;

margin:10px;

}

</style>

</head>

<body>

<form id="form1" runat="server">

<asp:XmlDataSource ID="srcmydata" DataFile="~/mydata.xml" runat="server" />

<div class="mybox">

<h3>(Scientists)TreeView</h3>

<asp:TreeView ID="checkboxlist1" DataSourceID="srcmydata" runat="server">

</asp:TreeView>

</div>

<div class="mybox">

<h3>(Scientists)Menu</h3>

<asp:Menu ID="bulletedlist1" DataSourceID="srcmydata" runat="server" />

</div>

</form>

</body>

</html>

 

 

 

Define an HTML style for the data to be put in. In this case, as above, a simple box

 

 

 

 

 

 

 

The datasource is the above XML file as specified here

 

 

 

 

 

 

 

Kurt Bingham 12/27/2007

Top


Using Parameters on a select

 

Return to the myDatabase SQL server express database and create a couple of tables

Create a table for Science Type
And a table for Scientists which will join to Science Types on smallint field SciType

 

 

Run the following Inserts

[Step 1]

insert into

dbo.ScienceType values

(0,'Physics')

insert into

dbo.ScienceType values

(1,'Astronomy')

insert into

dbo.ScienceType values

(2,'Comp-Sci')

insert into

dbo.ScienceType values

(3,'Biology')

insert into

dbo.ScienceType values

(4,'Chemistry')

 

[Step 3]

 

Run a quick Select

select

Name, Description from

dbo.Scientists A join dbo.ScienceType B

on A.SciType = B.SciType

 

Result Set

Carl Sagan Astronomy
Isaac Asimov Chemistry
John Mccarthy Comp-Sci
Marvin Minsky Comp-Sci
Richard Dawkins Biology
Schwartzchild Astronomy
Stephen Hawking Physics

 

[Step 2]

insert into dbo.Scientists values

('Marvin Minsky',2)

insert into dbo.Scientists values

('John Mccarthy',2)

insert into dbo.Scientists values

('Richard Dawkins',3)

insert into dbo.Scientists values

('Carl Sagan',1)

 

insert into dbo.Scientists values

('Isaac Asimov',4)

insert into dbo.Scientists values

('Stephen Hawking',0)

insert into dbo.Scientists values

('Schwartzchild',1)

 

 

 

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Parameters and a lookup table</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:DropDownList ID="SciType" DataSourceID="srcSciType" DataTextField="Description"

datavaluefield="SciType"

runat="server" />

<asp:Button

id="buttonSelect"

text="Select"

ToolTip="Select Science Type"

runat="server"

/>

<asp:Gridview ID="gridScientists" DataSourceID="srcScientists" runat="server" />

<asp:sqldatasource id="srcSciType" ConnectionString="Data Source=DLAHXXXXX\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True"

selectcommand="Select SciType, Description from dbo.ScienceType"

runat="server" />

<asp:SqlDataSource ID="srcScientists" ConnectionString="Data Source=DLAXXXXX\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True"

SelectCommand ="select Name, Description from dbo.Scientists

A join dbo.ScienceType B on A.SciType = B.SciType where A.SciType = @SciType"

runat="server">

<SelectParameters >

<asp:ControlParameter

name="SciType"

type="int16"

controlid="SciType" />

</SelectParameters>

</asp:SqlDataSource>

</div>

</form>

</body>

</html>

 

Create a drop down list bound to the datasource below, namely, that of the look up list. The datavaluefield is the actual 'value' of the control where as the DataTextField is what is displayed.

 

 

The Gridview's datasource is a select command which selects by SciType where SciType comes from the above DropDownList

The srcSciType simply queries to get all of the valid SciType from the SciType table in accordance with the SQL select shown here. These fields are the ones bound in the dropdownlist.

 

Finally, the grid view executes its selectcommand where the SciType = @SciType, and the @SciType parameter is bound to the value of the dropdownList at the top.

 

 

 

The control parameter definition. An Int16 is substituted for
SmallInt used in the database.

 

 

 

 

 

Kurt Bingham 12/27/2007

Top


Using ItemTemplate

The above examples use ItemTemplates and you can intuitively see how they can be used for various operations. In the next example, the ItemTemplate is used to create hyperlinks to Scientists homepages

First go into Design Mode for the Scientists table and add a new field

Design mode of Scientists table

update dbo.Scientists

set HomePage='http://web.media.mit.edu/~minsky/' where

Name = 'Marvin Minsky'

update dbo.Scientists

set HomePage='http://www-formal.stanford.edu/jmc/' where

Name = 'John Mccarthy'

update dbo.Scientists

set HomePage='http://richarddawkins.net' where

Name = 'Richard Dawkins'

 

update dbo.Scientists

set HomePage='http://www.carlsagan.com/' where

Name = 'Carl Sagan'

update dbo.Scientists

set HomePage='http://www.asimovonline.com/asimov_home_page.html' where

Name = 'Isaac Asimov'

update dbo.Scientists

set HomePage='http://www.hawking.org.uk/home/hindex.html' where

Name = 'Stephen Hawking'

update dbo.Scientists

set Name = 'Karl SwartzChild',

HomePage = 'http://en.wikipedia.org/wiki/Karl_Schwarzschild'

where Name = 'Schwartzchild'

 

Run the following updates (also corrects Schwartzchild's misspelled last name and gives him his own homepage at Wikipedia, though he's long dead of course--though Asimov and Sagan are as well unfortunately).

 

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>HomePages</title>

<style type="text/css">

</style>

</head>

<body>

<form id="form1" runat="server">

<div >

<asp:Repeater

id="RptScientists"

datasourceid="srcScientists" runat="server">

<itemtemplate>

<asp:HyperLink ID="scientists" Text='<%#eval("Name") %>' NavigateUrl = '<%#eval("HomePage") %>' runat="server" />

<br />

</itemtemplate>

</asp:Repeater>

<asp:SqlDataSource ID="srcScientists" ConnectionString="Data Source=PDUO\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True"

selectcommand="Select Name, Description, HomePage from dbo.Scientists A join dbo.ScienceType B on A.SciType = B.SciType"

runat="server" >

</asp:SqlDataSource>

</div>

</form>

</body>

</html>

 

The Repeater "rptScientists" is bound to the datasource "srcScientists" which as we know from above, has a "HomePage" field with the URL of the scientist's homepage. The ItemTemplate for the repeater basically spells out what else needs to be done using a hyperlink for the ItemTemplate. The <%#Eval function simply gets the field value from each row in the datasource.

 

Top

12/28/2007 Kurt Bingham


Two Way Databinding

Currently, the Scientist table is defined as follows:

 

It isn't much trouble to add an ID field, an integer as the new primary key. In order to do this, follow these steps

Insert a new field, ID, of type int

Remove the Primary Key property of Name, now the 2nd column

You must leave the "Allow Nulls" box checked for ID (and thus cannot make it the primary key) because when you attempt to save it, it will automatically rebuild the table structure and attempt to insert NULL values for the ID field and promptly return an error. Instead, save the table like so, update the data with a unique ID field using the next step, and then return to set the ID as its primary key.

 

DECLARE @ID int;

DECLARE @Scientist nvarchar(50);

DECLARE @message varchar(80);

DECLARE @SciType int;

set @ID = 1;

DECLARE cnt_cursor CURSOR for

select [Name], SciType from Scientists;

OPEN cnt_cursor

FETCH NEXT from cnt_cursor

into @Scientist, @SciType;

update Scientists set ID= @ID where [Name] = @Scientist;

WHILE @@FETCH_STATUS = 0

BEGIN

PRINT ' '

SELECT @message= str(@ID) + '----- Scientist: ' +

@Scientist

PRINT @message

FETCH NEXT from CNT_CURSOR

into @Scientist, @SciType;

set @ID = @ID + 1

update Scientists set ID= @ID where [Name] = @Scientist;

END

close cnt_Cursor;

DEALLOCATE cnt_cursor;

 

Or you can just use this (less fun)

insert into dbo.Scientists

select ROW_NUMBER() over (order by NAME) as 'Num',

Name, SciType,HomePage from dbo.Scientists

 

 

 

Transaction-SQL

This code of course is done in the query pane of SQL Server Express.

A simple cursor is used (which is fine on this small set of data) to get me out of my predicament of needing to create a new primary key on a table with a different key and a new ID to be determined on a row-by-row basis. 

This simply adds a counter ID as int to the data and updates each row, but you could just as easily create some other data type for the ID and create a key on other information about the author (initials + a counter or whatever).

After this is done, the ID field can be set to primary key in Design mode and saved.

 

Now to display the contents in a web page capable of updating the data based on the new primary key--which gives the option of updating the name as well, since it is no longer the primary key.

The page as it is displayed. Moving from record to record shows the editable fields in textboxes, and the user simply edits their contents and clicks the update button, which executes an update statement base don the new ID key created.

Code is shown below.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>two_way_databinding</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:FormView ID="frmScientists" DataKeyNames="ID" datasourceid="srcScientists" DefaultMode="edit"

allowpaging="true" runat="server" Width="352px">

<EditItemTemplate>

<asp:Label ID="lblName" Text="Name: " AssociatedControlID ="txtName" runat="server" />

<asp:TextBox ID="txtName" text='<%#bind("Name") %>' runat="server" />

<br />

<asp:Label ID="lblHomePage" Text="HomePage: " AssociatedControlID ="txtHomePage" runat="server" />

<asp:TextBox ID="txtHomePage" Text='<%#bind("Homepage") %>' runat="server" />

<br />

<asp:Button ID="btnUpdate" Text="Update" CommandName="Update" runat="server" />

</EditItemTemplate>

</asp:FormView>

<asp:SqlDataSource ID="srcScientists" runat="server"

ConnectionString="Data Source=DLAXXXXX\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True"

SelectCommand="Select ID, Name, Homepage from dbo.Scientists"

Updatecommand="Update dbo.Scientists set Name=@Name, Homepage=@HomePage where ID = @ID"

/>

</div>

</form>

</body>

</html>

 

Add a Formview with the Datasource given at the bottom, and create the itemtemplate as shown to the left. The btnUpdate member of the item template executes the datasource's associated Update statement with the bound parameters inside, in this case, with Name and Homepage
A variant allowing the insertion of data, although SciType, which is an int and is bound to another table, is automatically set to 1.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Public conn = "Data Source=PDUO\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True"

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id="Head1" runat="server">

<title>two_way_databinding</title>

</head>

<body>

<form id="form1" runat="server">

<asp:FormView ID="frmScientists" DataKeyNames="ID" datasourceid="srcScientists" DefaultMode="Edit"

allowpaging="True" runat="server" Width="352px">

<EditItemTemplate>

<asp:Label ID="lblName" Text="Name: " AssociatedControlID ="txtName" runat="server" />

<asp:TextBox ID="txtName" text='<%#bind("Name") %>' runat="server" />

<br />

<asp:Label ID="lblSciType" Text="Field:" runat="server" />

<asp:textbox ID="txtSciType" Text='<%#bind("Description")%>' runat="server" />

<br />

<asp:Label ID="lblHomePage" Text="HomePage: " AssociatedControlID ="txtHomePage" runat="server" />

<asp:TextBox ID="txtHomePage" Text='<%#bind("Homepage") %>' runat="server" />

<br />

<asp:Button ID="btnUpdate" Text="Update" CommandName="Update" runat="server" />

<asp:Button id="btnNew" Text="New" CommandName="New" runat="server" />

</EditItemTemplate>

<InsertItemTemplate>

<asp:Label ID="lblName" Text="Name: " AssociatedControlID ="txtName" runat="server" />

<asp:TextBox ID="txtName" text='<%#bind("Name") %>' runat="server" />

<br />

<asp:Label ID="lblSciType" Text="Field:" runat="server" />

<asp:textbox ID="txtSciType" Text='<%#bind("Description")%>' runat="server" />

<br />

<asp:Label ID="lblHomePage" Text="HomePage: " AssociatedControlID ="txtHomePage" runat="server" />

<asp:TextBox ID="txtHomePage" Text='<%#bind("Homepage") %>' runat="server" />

<br />

<asp:button ID="btnInsert" Text = "Insert" CommandName="Insert" runat="server"/>

<br />

</InsertItemTemplate>

</asp:FormView>

<asp:SqlDataSource ID="srcScientists" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString %>"

SelectCommand="Select ID, Name, Description, Homepage from dbo.Scientists A join dbo.ScienceType B on A.SciType = B.SciType"

Updatecommand="Update dbo.Scientists set Name=@Name, Homepage=@HomePage where ID = @ID"

InsertCommand="Insert into dbo.Scientists (ID,[Name],SciType,HomePage)select (select max(ID) from dbo.Scientists)+1,@Name,1,@Homepage" >

</asp:SqlDataSource>

<asp:SqlDataSource ID="srcSciType" runat="server" ConnectionString="<%$ connectionstrings:mydatabaseconnectionstring %>"

selectcommand="select SciType,Description from dbo.ScienceType"></asp:SqlDataSource>

 

</form>

</body>

</html>

 

Of note is the addition of an InsertItemTemplate as well as the addition of a 'New' button in the EditItemTemplate, which basically forces the addition of a row.

 

Computing the ID of the new row, because it's an ascending int, is done with a slightly more involved SQL :

...

Insert into dbo.Scientists (ID,[Name],SciType,HomePage)select (select max(ID) from dbo.Scientists)+1,@Name,1,@Homepage

...

The MAX(ID) is used to compute the new row, and the parameters are gathered from the text fields. Notice however that the SciType, an int, is automated to 1. It's also not referenced in the Update. In order to deal with this, a list box must be inserted bound to a datasource of the SciType table, in which the text is the Description, and the Value is the SciType int field.

That value would then be inserted while the description would be displayed.

 

 

12/31/2008 Kurt bingham

Top


ObjectDataSource  (pg 714.)

Imports Microsoft.VisualBasic

Imports System

Imports System.Web.Configuration

Imports System.Collections.Generic

Imports System.Data.SqlClient

Imports System.data

Public Class MyLists

 

Public Function rtnNumbers() As List(Of String)

Dim Nums As New List(Of String)

For k As Integer = 1 To 20

Nums.Add(k.ToString)

Next

Return Nums

End Function

Public Function rtnDataset(ByVal SqlStr As String) As DataSet

Dim conn As SqlConnection = New SqlConnection("Data Source=PDUO\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True")

Dim myDataset As DataSet

Dim dataAdapter As SqlDataAdapter

myDataset = New DataSet

dataAdapter = New SqlDataAdapter(SqlStr, conn)

dataAdapter.Fill(myDataset)

Return myDataset

End Function

End Class

 

Two different functions. One returns a list(of string) and the other returns a Dataset.

 

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

'this is one way of doing it the other way is do put it directly in the declaration as shown below

Me.srcDataSet.SelectParameters(0).DefaultValue = "Select * from dbo.Scientists"

End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>obj_data_src</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:ObjectDataSource ID="srcNums" TypeName="MyLists" SelectMethod="rtnNumbers" runat="server" />

<asp:ObjectDataSource ID="srcDataSet" TypeName="MyLists" SelectMethod="rtnDataSet" runat="server" >

<selectParameters>

<asp:parameter name="SQLstr" Type="string" DefaultValue="Select * from dbo.Scientists"/>

</selectParameters>

</asp:ObjectDataSource>

<asp:gridview id="grdDataset" datasourceid="srcDataSet" runat="server"/>

<asp:gridview ID="grdNums" DataSourceID="srcNums" runat="server" />

</div>

</form>

</body>

</html>

 

The best explanation for the purpose ObjectDataSource can be found here, but intuitively, you can see how the Gridview objects are able to bind to different types of data, the first being a simple List.

'The ObjectDataSource control acts as a data interface for data-bound controls such as the GridView, FormView, or DetailsView controls. You can use these controls to display and edit data from a middle-tier business object on an ASP.NET Web page.'

1/6/2008 Kurt Bingham

Top


ObjectDataSource (Updating table info in a GridView/Selecting on a dropdownbox)

Imports Microsoft.VisualBasic

Imports System

Imports System.Web.Configuration

Imports System.Collections.Generic

Imports System.Data.SqlClient

Imports System.data

Public Class Publics

Public Const myConn = "Data Source=DLAHD25V11\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True"

End Class

 

Public Class MyLists

Public Function rtnNumbers() As List(Of String)

Dim Nums As New List(Of String)

For k As Integer = 1 To 5

Nums.Add(k.ToString)

Next

Return Nums

End Function

Public Function rtnDataset(ByVal SqlStr As String) As DataSet

Dim conn As SqlConnection = New SqlConnection(Publics.myConn)

Dim myDataset As DataSet

Dim dataAdapter As SqlDataAdapter

myDataset = New DataSet

dataAdapter = New SqlDataAdapter(SqlStr, conn)

dataAdapter.Fill(myDataset)

Return myDataset

End Function

End Class

Public Class Scientists

Public Sub UpdateScientist(ByVal id As Integer, ByVal name As String, ByVal homepage As String)

Dim conn As New SqlConnection(Publics.myConn)

Dim cmd As New SqlCommand()

cmd.Connection = conn

cmd.CommandText = "Update dbo.Scientists set Name = @Name, HomePage=@Homepage where id=@id"

cmd.Parameters.AddWithValue("@Name", name)

cmd.Parameters.AddWithValue("@HomePage", homepage)

cmd.Parameters.AddWithValue("@ID", id)

conn.Open()

cmd.ExecuteNonQuery()

End Sub

Private Function GeneralGet(ByVal SQL As String) As SqlDataReader

Dim conn As New SqlConnection(Publics.myConn)

Dim cmd As New SqlCommand(SQL)

cmd.Connection = conn

conn.Open()

Return cmd.ExecuteReader

End Function

Private Function GeneralGet(ByVal cmd As SqlCommand) As SqlDataReader

Dim conn As New SqlConnection(Publics.myConn)

cmd.Connection = conn

conn.Open()

Return cmd.ExecuteReader

End Function

Public Function GetScientists() As SqlDataReader

Return GeneralGet("Select ID, Name, Homepage from dbo.Scientists ")

End Function

Public Function GetScientists(ByVal SciType As Int16) As SqlDataReader

Dim cmd As New SqlCommand("Select ID,Name,HomePage from dbo.Scientists where SciType=@SciType")

cmd.Parameters.AddWithValue("@SciType", SciType)

Return GeneralGet(cmd)

End Function

Public Function GetScitypes() As SqlDataReader

Dim conn As New SqlConnection(Publics.myConn)

Dim cmd As New SqlCommand()

cmd.Connection = conn

cmd.CommandText = "select SciType, Description from dbo.ScienceType"

conn.Open()

Return cmd.ExecuteReader

End Function

End Class

 

 

 

In the APP_CODE subdirectory, update the visual basic module from the last aspx page.

In this case, I've added a "Scientists" class which has an Update and a few GetScientists function overloads returning SQLDataReader types, and these are used to return filtered data on selects.

 

Of interest here  are the

GetSciTypes which returns the list of SciTypes and their Descriptions (for the DropDownBox)

GetScientists(sciType as Int16) which returns all of the rows with the given science Discipline

These will be used in the next two pages.

 

Top


ObjectDataSource (Update) - Pg 730

Updating a table. This uses the VB code from the class given above, which must be put in the APP_CODE subdirectory.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>objdat_src_scientists</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:GridView ID="grdSci" DataSourceID="srcSci" DataKeyNames="ID" AutoGenerateEditButton="true"

runat="server">

</asp:GridView>

<asp:ObjectDataSource ID="srcSci" TypeName="Scientists" SelectMethod="GetScientists"

updatemethod="UpdateScientist" runat="server">

<UpdateParameters>

<asp:Parameter Name="ID" />

<asp:parameter Name="Name" />

<asp:Parameter Name="HomePage" />

</UpdateParameters>

</asp:ObjectDataSource>

</div>

</form>

</body>

</html>

 

Most of the work is done in the vb code a few rows above here. It defines how the update is carried out. Once the code for this is put into play, it's just a matter of defining the class and the "SelectMethod" and the "UpdateMethod". If the keys and values match, it does the rest of the work for you.

1/6/2008

ObjectDataSource(Select parameter dropdownlist) -Pg 730

Dropdownbox to parameterize a query. This uses the VB code from the class given above, which must be put in the APP_CODE subdirectory.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Selecting Data based on Parameters</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:DropDownList ID="ddSciTypes" DataSourceID="srcScitypes"

datatextfield="Description"

datavaluefield="Scitype"

runat="server" />

<asp:Button ID="btnSelect" text="Select" runat="server" />

<asp:GridView ID="grdScientists" DataSourceid="srcScientists" runat="server" />

<asp:ObjectDataSource ID="srcScitypes" TypeName="Scientists" SelectMethod="GetSciTypes" runat="server" />

<asp:ObjectDataSource ID="srcScientists" TypeName="Scientists"

SelectMethod="GetScientists" runat="server" >

<SelectParameters>

<asp:controlparameter

Name="SciType" ControlID="ddScitypes" />

</SelectParameters>

</asp:ObjectDataSource>

</div>

</form>

</body>

</html>

 

Most of the work is done in the vb code a few rows above here. It defines how the select where (field = parameter) is carried out. Once the code for this is put into play, it's just a matter of defining the class dropdownbox text, id, and datasource properties as well as the GridViews properties and its datasource properties.

1/6/2008 Kurt Bingham

Top


ObjectDataSource GuestBook

A simple guestbook page that inserts the comments into a table
Setting up the table:

I created a table with the following properties, based on Walther's use of his guestbook table

The fields are shown to the left

 

Set up the ID columns to autonumber using the Identity Specification lists in the GUI table def.

And for the Date field, set the default value to

  • getdate()

Which will get the date at time of insertion if the field is empty.

 

Public Class myGuestBook

Public Function GetEntries() As SqlDataReader

Dim conn As New SqlConnection(Publics.myConn)

Dim cmd As New SqlCommand("Select ID, IPAddress, Comment,Date from dbo.guestbook_tbl")

cmd.Connection = conn

conn.Open()

Return cmd.ExecuteReader(CommandBehavior.CloseConnection)

End Function

Public Sub AddNew(ByVal IPAddress As String, ByVal comment As String)

Dim conn As New SqlConnection(Publics.myConn)

Dim cmd As New SqlCommand("Insert into guestbook_tbl (IPaddress,Comment) values(@IPAddress, @comment)")

cmd.Parameters.AddWithValue("@IPAddress", IPAddress)

cmd.Parameters.AddWithValue("@Comment", comment)

cmd.Connection = conn

conn.Open()

cmd.ExecuteNonQuery()

End Sub

End Class

 

The myGuestBook class that goes in your App_Code directory. The insert only deals with the IPAddress and comment because the ID and Date fields will populate automatically when you insert the data.

 

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Protected Sub srcGuestbook_inserting(ByVal sender As Object, ByVal e As ObjectDataSourceMethodEventArgs)

'notice e passes the object by reference, thus we can set the parameter

'the byval doesn't apply to objects

e.InputParameters.Add("IPAddress", Request.UserHostAddress)

End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Guestbook</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:FormView ID="frmGuestbook" DataSourceID="srcguestbook"

defaultmode="Insert"

runat="server">

<InsertItemTemplate>

<asp:Label ID="lblComment" Text="Comment:" AssociatedControlID="txtComment" runat="server" />

<br />

<asp:TextBox ID="txtComment" Text='<%#bind("comment") %>' TextMode="multiline" Columns="60"

rows="4" runat="server" />

<br />

<asp:Button ID="btnInsert" Text="Add Entry" CommandName="Insert" runat="server" />

</InsertItemTemplate>

</asp:FormView>

<asp:GridView ID="grdGuestbook" DataSourceID="srcGuestBook" runat="server" />

<asp:ObjectDataSource ID="srcguestbook" TypeName="MyGuestbook" SelectMethod="GetEntries"

insertmethod="AddNew" OnInserting="srcGuestbook_Inserting"

runat="server" />

</div>

</form>

</body>

</html>

 

This code simply makes use of the OnInserting method to run some code to fill the IPAddress field.

Most of the coding I have done in the past has been without making use of these fancy controls, so it would have been routine to be running all sorts of code when a button was pressed or during some other event. Til now, there hasn't been a need for event code--that speaks volumes about how practical these new controls are.

 

 

 

1/8/08

Top


Disconnected Data Access

Data can be updated and manipulated in a datatable kept locally (after retrieving from database). Using a builder to create SQL statements for Update, Delete, etc, you can then force a transaction to the database but in the meantime handle edits, deletes, inserts locally

<%@ Page Language="VB" %>

<%@ Import Namespace="system.data" %>

<%@ Import Namespace="system.data.sqlclient" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Private Dad As SqlDataAdapter

Private Mytable As DataTable

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

Dim conn As New SqlConnection("Data Source=PDUO\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True")

Dad = New SqlDataAdapter("select ID,Name, SciType, Homepage from dbo.Scientists", conn)

Dim builder As New SqlCommandBuilder(dad)

Mytable = New DataTable()

dad.fill(Mytable)

repeater1.DataSource = Mytable

repeater1.DataBind()

End Sub

Protected Sub lnkUpdate_click(ByVal sender As Object, ByVal e As EventArgs)

For i As Integer = 0 To repeater1.Items.Count - 1

Dim item As RepeaterItem = repeater1.Items(i)

Dim txtName As TextBox = CType(item.FindControl("txtName"), TextBox)

Dim txtHome As TextBox = CType(item.FindControl("txtHome"), TextBox)

mytable.Rows(i)("Name") = txtName.Text

mytable.Rows(i)("HomePage") = txtHome.Text

Next

Dim numupdated As Integer = dad.Update(mytable)

End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>disconnected data</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Repeater ID="repeater1" enableviewstate="false" runat="server" >

<ItemTemplate>

<asp:TextBox ID="txtName" Text='<%#eval("Name") %>' runat="server">

</asp:TextBox>

<asp:TextBox ID="txtHome" Text='<%#eval("HomePage")%>' runat="server">

</asp:TextBox>

<asp:LinkButton ID="lnkUpdate" Text="Update" runat="server" OnClick="lnkUpdate_Click" />

<br />

</ItemTemplate>

</asp:Repeater>

</div>

</form>

</body>

</html>

 

See Pg 834 of Stephen text. A simple repeater is used with textboxes. I didn't check to see if things had changed and simply updated all rows. Key points are the Find function for the repeater item and the update. You can also choose UpdateBatchSize and other things as well before doing this update.

 

 

Return Home