How to use the GridView control

acceptableseashoreΑσφάλεια

5 Νοε 2013 (πριν από 3 χρόνια και 9 μήνες)

133 εμφανίσεις

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
1

Chapter 14

How to use the

GridView control

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
2

Objectives

Applied



Use a GridView control with bound fields to format and display
the data in a data source.



Use a GridView control to update the data in a data source.



Use events raised by a GridView control to
check for exceptions.



Use the SQL data source for a GridView control to insert a row
into the database.



Use template fields and validation controls with a GridView
control.

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
3

Objectives (cont.)

Knowledge



Describe the basic functions that are provided by the
GridView
control.



Describe the difference between a bound field and a template
field.



Explain what a command field is and how it’s used in a GridView
control.



Explain what the before
-
action and after
-
action events of a
GridView control are typically used f
or.



Describe how you can provide for adding rows to a GridView
control.

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
4

A GridView control that provides for updating a
table

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
5

The asp
x code for the GridView control

<asp:GridView ID="GridView1" runat="server"


AutoGenerateColumns="False"

Data
SourceID="SqlDataSource1"


DataKeyNames="CategoryID" >

<Columns>

<asp:BoundField DataField="CategoryID"


HeaderText="ID"

ReadOnly="True" SortExpression="CategoryID">

<ItemStyle Width="100px" />

<
/asp:BoundField>

<asp:BoundField DataField="ShortName"


HeaderText="Short Name"

SortExpression="ShortName">

<ItemStyle Width="150px" />

</asp:BoundField>

<asp:BoundField DataField="LongName"



HeaderText="Long Name"

SortExpression="LongName">

<ItemStyle Width="200px" />

</asp:BoundField>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
6

The aspx code for the GridView control (cont.)

<asp:CommandField ButtonType="Button"


ShowEditButto
n="True"

CausesValidation="False" />

<asp:CommandField ButtonType="Button"


ShowDeleteButton="True"

CausesValidation="False" />

</Columns>

</asp:GridView>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
7

Basic attributes of the GridView control

Attribute

Description

ID

The ID of the control.

Runat

Must specify “server.”

DataSourceID

The ID of the data source to bind to.

DataKeyNames

The names of the primary key fields
separated by commas.

AutoGenerateColum
ns

Specifies whether the control’s columns
should be automatically generated.

SelectedIndex

Specifies the row to be initially selected.

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
8

The Fields dialog box

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
9

Commonly used field properties



DataField



DataFormatString



HtmlEncode



ItemStyle, Width



ReadOnly



NullDisplayText



ConvertEmptyStringToNull



HeaderText



ShowHeader

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
10

Column field elements

Element

Description

Columns

The columns that are displayed by a GridView
control.

asp:BoundField

A field bound to a data source column.

asp:ButtonField

A field that displays a button.

asp:CheckBoxField

A field that displays a check bo
x.

asp:CommandField

A field that contains Select, Edit, Delete,
Update, or Cancel buttons.

asp:HyperlinkField

A field that displays a hyperlink.

asp:ImageField

A field that displays an image.

asp:TemplateField

Lets you create a column with custom content.

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
11

Style elements

Element

Description

RowStyle

The style used for data rows.

AlternatingRowStyle

The style used for alternating data rows.

SelectedRowStyle

The style used when the row is selected.

EditRowStyle

The style used when the row is being edited.

Empt
yDataRowStyle

The style used when the data source is empty.

ItemStyle

The style used for an individual field.

HeaderStyle

The style used to format the header row.

FooterStyle

The style used to format the footer row.

PagerStyle

The style used to format the
pager row.

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
12

The aspx code for a control that uses field and
style elements

<asp:GridView ID="GridView1" runat="server"


AutoGenerateColumns="False"

DataKeyNames="CategoryID"
DataSourceID="SqlDataSource1">

<Columns>

<asp:
BoundField DataField="CategoryID" HeaderText="ID"


readOnly="true" >



<ItemStyle Width="100px" />


</asp:BoundField>

.

.

</Columns>

<HeaderStyle BackColor="LightGray" ForeColor="White"

Font
-
Bold="True" />

<Row
Style BackColor="White" ForeColor="Black" />

<SelectedRowStyle BackColor="Gray" ForeColor="White"

Font
-
Bold="True" />

<FooterStyle BackColor="LightGray" ForeColor="Blue" />

<PagerStyle BackColor="LightGray" ForeColor="Blue"


HorizontalAlign="Center" />

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
13

A GridView control with sorting enabled

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
14

The aspx code for the control

<asp:GridView ID="GridView1" runat="server"


AllowSorting="True"

AutoGenerateColumns="False" DataKeyNames="ProductID"


DataSourceID="SqlDataSource1">

<Columns>

<asp:BoundField DataField="ProductID"


HeaderText="ID"

ReadOnly="True"
SortExpression="ProductID"
>

<HeaderStyle HorizontalAlign="Left" />

<ItemStyle
Width="75px" />

</asp:BoundField>

<asp:BoundField DataField="Name" HeaderText="Name"


SortExpression="Name"
>

<HeaderStyle HorizontalAlign="Left" />

<ItemStyle Width="200px" />

</asp:BoundField
>

<asp:BoundField DataField="CategoryID"


HeaderText="Category"


SortExpression="CategoryID, Name"
/>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
15

The aspx code for the control (cont.)

<asp:BoundField DataField="UnitPrice"


DataFormatString="{0:c
}"

HtmlEncode="False" HeaderText="Unit Price">

<ItemStyle Width="85px"


HorizontalAlign="Right" />

<HeaderStyle HorizontalAlign="Right" />

</asp:BoundField>

<asp:BoundField DataField
="OnHand"


HeaderText="On Hand">

<ItemStyle Width="85px"


HorizontalAlign="Right" />

<HeaderStyle HorizontalAlign="Right" />

</asp:BoundField>

</Columns>

<HeaderStyle BackColor="Light
Gray" />

</asp:GridView>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
16

A GridView with paging enabled

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
17

Th
e
aspx
code for the GridView control

<asp:GridView ID="GridView1" runat="server"


AllowPaging="True"


AutoGenerateColumns="False" DataKeyNames="ProductID"

DataSourceID="SqlDataSour
ce1">

<Columns>

<asp:BoundField DataField="ProductID"


HeaderText="ID"

ReadOnly="True">

<HeaderStyle HorizontalAlign="Left" />

<ItemStyle Width="75px" />

</asp:BoundField>

<a
sp:BoundField DataField="Name" HeaderText="Name">

<HeaderStyle HorizontalAlign="Left" />

<ItemStyle Width="200px" />

</asp:BoundField>

<asp:BoundField DataField="CategoryID"


HeaderText="Category" />

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
18

T
he
aspx
code for the GridView control (cont.)

<asp:BoundField DataField="UnitPrice"


DataFormatString="{0:c}"

HtmlEncode="False" HeaderText="Unit Price">

<ItemStyle Width="85px"


HorizontalAl
ign="Right" />

<HeaderStyle HorizontalAlign="Right" />

</asp:BoundField>

<asp:BoundField DataField="OnHand"


HeaderText="On Hand">

<ItemStyle Width="85px"


HorizontalAlign="Right" />

<HeaderStyle HorizontalAlign="Right" />

</asp:BoundField>

</Columns>

<HeaderStyle BackColor="LightGray" />


<PagerStyle BackColor="LightGray"


HorizontalAlign="Center" />

</asp:GridView>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
19

Attributes of the GridView control that affect
paging

Attribute

Description

AllowPaging

Set to True to enable paging.

PageSize

Specifies the number of rows to display on each
page. The default is 10.

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
20

Attributes of the PagerSettings element



Mode



FirstPageText



FirstPageImageUrl



Previou
sPageText



PreviousPageImageUrl



NextPageText



NextPageImageUrl



LastPageText



LastPageImageUrl



PageButtonCount



Position



Visible

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
21

A PagerSettings element

<PagerSettings Mode="NextPreviousFirstLast"

NextPageText="Next"

PreviousPageText="Prev"

FirstPageText="First"

LastPageText="Last" />

The resulting pag
er area

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
22

The Product List application

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
23

The Default.aspx file

<%@ Page Language="VB" AutoEventWireup="false"
CodeFile="Default.aspx.vb" Inheri
ts="_Default" %>


<!DOCTYPE html PUBLIC "
-
//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">


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

<head runat="server">

<title>Chapter 14: Product List</title>

</head>

<body>

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

<div>

<asp:Image ID="Image1" runat="server"


ImageUrl="~/Images/banner.jpg" />

<br /><br />

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
24

The Default.aspx file (cont.)

<asp:GridView ID="GridView1" runat="server"

AllowSorting="
True"


AllowPaging="True" PageSize="8"

DataKeyNames="ProductID"


DataSourceID="SqlDataSource1"

AutoGenerateColumns="False"

CellPadding="4" GridLines="None"


ForeColor="Black">


<Columns>

<asp:BoundField DataField="ProductID"


HeaderText="ID"

ReadOnly="True"


SortExpression="ProductID">

<HeaderStyle HorizontalAlign="Left" />

<ItemSt
yle Width="75px" />

</asp:BoundField>

<asp:BoundField DataField="Name"


HeaderText="Name"

SortExpression="Name">

<HeaderStyle HorizontalAlign="Left" />


<ItemStyle Width="200px" />

</asp:BoundField>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
25

The Default.aspx file (cont.)

<asp:BoundField DataField="CategoryID"

HeaderText="Category"

SortExpression="CategoryID, Name" />

<asp:BoundField DataField="UnitPrice"


DataFormatString="{0:c}"

HtmlEncode="False"

HeaderText="Unit Price">

<ItemStyle HorizontalAlign="Right" />

</asp:BoundField>

<asp:BoundField DataField="OnHand"


HeaderText="On Hand">

<ItemStyle HorizontalAlign="Right" />

</asp:BoundField>

</Columns>

<HeaderStyle BackColor="Silver" Font
-
Bold="True"

ForeColor="White" />

<RowStyle BackColor="White" ForeColor="Black" />

<AlternatingRowStyle BackColor="WhiteSmoke"

ForeColor="Black" />

<FooterStyle BackColor="Silver" Font
-
Bold="True"

ForeColor="White" />

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
26

The Default.aspx file (cont.)

<PagerStyle BackColor="Silver" ForeColor="Blue"

HorizontalAlign="Center" />

<PagerSettings Mode="NumericFirstLast" />

</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource
1"

runat="server"

ConnectionString=

"<%$ ConnectionStrings:HalloweenConnection %>"

SelectCommand="SELECT [ProductID], [Name],

[CategoryID], [UnitPrice], [OnHand]

FROM [Pr
oducts] ORDER BY [ProductID]">

</asp:SqlDataSource>

</div>

</form>

</body>

</html>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
27

The Fields dialog box for working with a
command field

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
28

Typical code to define command fields

<asp:CommandField ButtonType="Button"

ShowEditButton="True"

CausesValidation="False" />

<asp:CommandField ButtonType="Button"

ShowDeleteButton="True"

CausesValidation="False" />

Attributes of th
e CommandField element

Attribute

Description

ButtonType

Specifies the type of button displayed in the
command field. Valid options are Button, Link, or
Image.

CausesValidation

Specifies whether validation should be performed
if the user clicks the button.

ValidationGroup

Specifies the name of the group to be validated if
CausesValidation is True.

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
29

Attributes that show buttons and set the text or
images they display

Button

Show

Text

Image

Cancel

ShowCancelButton

CancelText

CancelImage

Delete

ShowDeleteButton

DeleteText

DeleteImage

Edit

ShowEditButton

EditText

EditImage

Select

ShowSelectButton

SelectT
ext

SelectImage

Update

n/a

UpdateText

UpdateImage

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
30

Events raised by the GridView control

Event

Raised when …

RowCancelingEdit

The Cancel button of a row in edit mode
is clicked.

RowDataBound

Data binding completes for a row.

RowDeleted

A row has been deleted.

RowDeleting

A row is about to be deleted.

RowEd
iting

A row is about to be edited.

RowUpdated

A row has been updated.

RowUpdating

A row is about to be updated.

SelectedIndexChanged

A row has been selected.

SelectedIndexChanging

A row is about to be selected.

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
31

An event handler for the RowUpdated event

Protected Sub GridView1_RowUpdated(ByVal sender As Object,_

ByVal e As _

System.Web.UI.WebControls.GridViewUpdatedEventArgs) _

Handles GridView1.RowUpdated

If e.Exception IsNot Nothing Then


lblError.Text = "
A database error has occurred.
" _

& e.Exception.Message

e.ExceptionHandled = True

e.KeepInEditMode = True

ElseIf e.AffectedRows = 0 Then

lblError.Text =


&
"
Another
user may have update
d that category."
_


&
"
Please try again."

End If

End Sub

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
32

Method and properties of the SqlDataSource class
for inserting rows

Method

Description

Insert
()

Executes the Insert command defined for
the data source.

Property

Description

InsertCommand

The Insert command to be executed.

InsertParameters
("
name
")

The para
meter with the specified name.

Property of the Parameter class for inserting rows

Property

Description

DefaultValue

The default value of a parameter. This value is
used if no other value is assigned to the parameter.

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
33

Code that uses a SqlDataSource control to insert
a row

Protected Sub btnAdd_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles btnAdd.Click

SqlDataSource1.InsertParameters("CategoryID")._

DefaultValue = txtID.Text


SqlDataSource1.InsertParameters("ShortName")._

DefaultValue = txtShortName.Text

SqlDataSource1.InsertParameters("LongName")._

DefaultValue = txtLongName.Text

Try

SqlDataSource1.Insert()

txtID.Text = ""

txtSho
rtName.Text = ""

txtLongName.Text = ""

Catch ex As Exception

lblError.Text = "
A database error

has
occurred. " _

& ex.Message

End Try

End Sub

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
34

The Category Maintenance application

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
35

The Default.aspx file

<%@ Page Language="VB" AutoEventWireup="false"
CodeFile="Default.aspx.vb" Inherits="_Default" %>


<!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>Chapter 14: Category Maintenance</title>

<style type="text/css">

.style1 {width: 100px;}

.style2 {width: 195px;}

</style>

</head>

<body>

<form id="form1" runat="s
erver">

<div>

<asp:Image ID="Image1" runat="server"

ImageUrl="~/Images/banner.jpg" />

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
36

The Default.aspx file (cont.)

<h2>Category Maintenance</h2>

<asp:GridView ID="GridView1" runat="server"

AutoGenerateColumns="False"

DataKeyNames="CategoryID"

DataSourceID="SqlDataSource1" ForeColor="Blac
k">

<Columns>

<asp:BoundField DataField="CategoryID"

HeaderText="ID" ReadOnly="True">

<HeaderStyle HorizontalAlign="Left" />

<ItemStyle Width="100px" />


</asp:BoundField>

<asp:BoundField DataField="ShortName"

HeaderText="Short Name">

<HeaderStyle HorizontalAlign="Left" />

<ItemStyle Width="150px" />

</asp:BoundFi
eld>

<asp:BoundField DataField="LongName"

HeaderText="Long Name">

<HeaderStyle HorizontalAlign="Left" />

<ItemStyle Width="200px" />

</asp:BoundField>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
37

The Default.aspx file (cont.)

<asp:CommandField ButtonType="Button"

ShowEditButton="True"

CausesValidation="False" />

<asp:CommandField ButtonType="Button"

ShowDe
leteButton="True"

CausesValidation="False" />

</Columns>

<HeaderStyle BackColor="Silver" Font
-
Bold="True"

ForeColor="White" />

<RowStyle BackColor="White" ForeColor="Black" />


<AlternatingRowStyle BackColor="WhiteSmoke"

ForeColor="Black" />

<EditRowStyle BackColor="Blue"

ForeColor="White" />

</asp:GridView>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
38

The Default.aspx file
(cont.)

<asp:SqlDataSource ID="SqlDataSource1"

runat="server"

ConflictDetection="CompareAllValues"

ConnectionString=

"<%$ ConnectionStrings:HalloweenConnection %>"

O
ldValuesParameterFormatString="original_{0}"

SelectCommand="SELECT [CategoryID], [ShortName],

[LongName]

FROM [Categories]"

DeleteCommand="DELETE FROM [Categories]

WHERE [CategoryID]
= @original_CategoryID

AND [ShortName] = @original_ShortName

AND [LongName] = @original_LongName"

UpdateCommand="UPDATE [Categories]

SET [ShortName] = @ShortName,

[Lon
gName] = @LongName

WHERE [CategoryID] = @original_CategoryID

AND [ShortName] = @original_ShortName

AND [LongName] = @original_LongName"

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
39

The Default.aspx fil
e (cont.)

InsertCommand="INSERT INTO [Categories]

([CategoryID], [ShortName], [LongName])

VALUES (@CategoryID, @ShortName,

@LongName)">

<DeleteParameters>

<asp
:Parameter Name="original_CategoryID"

Type="String" />

<asp:Parameter Name="original_ShortName"

Type="String" />

<asp:Parameter Name="original_LongName"

Type="St
ring" />

</DeleteParameters>

<UpdateParameters>

<asp:Parameter Name="ShortName"

Type="String" />

<asp:Parameter Name="LongName"

Type="String" />


<asp:Parameter Name="original_CategoryID"

Type="String" />

<asp:Parameter Name="original_ShortName"

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
40

The Default.aspx file (cont.)

<asp:Parameter Name="original_LongName"

Type="String" />

</UpdateParameters>

<InsertParameters>

<asp:Parameter Name="CategoryID"


Type="String" />

<asp:Parameter Name="ShortName"

Type="String" />

<asp:Parameter Name="LongName"

Type="String" />

</InsertParameters>

</asp:SqlDataSource><br />

To create a new category, enter the category

information and click Add New Category.<br />

<asp:Label ID="lblError" runat="server"

EnableViewState="False"

ForeColor="Red"></asp:Label><br /><br />

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
41

The Default.aspx file (cont.)

<table>

<tr>

<td
class="style1"
>ID:</td>

<td
class="style1"
>

<asp:TextBox ID="txtID" runat="server"


Width="100px"




MaxLength="10"
>

</asp:TextBox></td>

<td
class="style
2
"
>

<asp:RequiredFieldValidator

ID="RequiredFieldValidator1"

runat="server" ControlToValidate="txtID"

E
rrorMessage="ID is a required field.">

</asp:RequiredFieldValidator></td>

</tr>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
42

The Default.aspx file (cont.)

<tr>

<td
class="style1"
>Short Name:</td>

<td
class="style1"
>

<asp:TextBox ID="txtShortName" runat="server"

Width="200px"



MaxLength="1
5
"
>


</asp:TextBox></td>

<td
class="style
2
"
>

<asp:RequiredFieldValidator

ID="RequiredFieldValidator2"

runat="server"

ControlToValidate="txtShortName"

E
rrorMessage=

"Short Name is a required field.">

</asp:RequiredFieldValidator></td>

</tr>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
43

The Default.aspx file (cont.)

<tr>

<td
class="style1"
>Long Name:</td>

<td
class="style1"
>

<asp:TextBox ID="txtLongName" runat="server"

Width="200px"



MaxLength="
5
0"
>


</asp:TextBox></td>

<td
class="style
2
"
>

<asp:RequiredFieldValidator

ID="RequiredFieldValidator3"

runat="server"

ControlToValidate="txtLongName"

Erro
rMessage=

"Long Name is a required field.">

</asp:RequiredFieldValidator></td>

</tr>

</table>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
44

The Default.aspx file (cont.)

<br />

<asp:Button ID="btnAdd" runat="server"

Text="Add New Category" />

</div>

</form>

</body>

</html>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
45

The Default.aspx.vb file

Partial Class _Default

Inherits System.Web.UI.Page


Protected Sub btnAdd_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) _

Handles btnAdd.Click

SqlDataSource1.InsertParameters("C
ategoryID")._

DefaultValue = txtID.Text

SqlDataSource1.InsertParameters("ShortName")._

DefaultValue = txtShortName.Text

SqlDataSource1.InsertParameters("LongName").

DefaultValue = txtLongName.Text


Try

SqlDataSource1.Insert()

txtID.Text = ""

txtShortName.Text = ""

txtLongName.Text = ""

Catch ex As Exception

lblError.Text =
_


"
A
database error

has
occurred
. " _


& ex.Message

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
46

The Default.aspx.vb file (cont.)

End Try

End Sub


Protected Sub GridView1_RowUpdated( _

ByVal sender As Object, _

ByVal e As _

System.Web.UI.WebControls.GridViewUpdatedEventArgs) _

Handles GridView1.RowUpdate
d

If e.Exception IsNot Nothing Then

lblError.Text =
_


"
A database error has occurred
. " _

& e.Exception.Message

e.ExceptionHandled = True

e.KeepInEditMode = True

ElseIf e.
AffectedRows = 0 Then

lblError.Text = "
Another
user may have
" _

&
"
updated
that category
. " _

& "Please try again."

End If

End Sub

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
47

The Default.aspx.vb file (cont.)

Protected Sub GridView1_RowDeleted(

ByVal sender As Object, _

ByVal e As _

System.Web.UI.WebControls.GridViewDeletedEventArgs) _

Handles GridView1.RowDeleted

If e.Exception IsNot
Nothing Then

lblError.Text =
_


"
A
database error

has
occurred
. " _

& e.Exception.Message

e.ExceptionHandled = True

ElseIf e.AffectedRows = 0 Then

lblError.Text =
"
Another
user may have
" _


& "
updated this
category. " _

& "Please try again."

End If

End Sub

End Class

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
48

How to edit templates

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
49

GridView template elements

Element

Description

ItemTemplate

The template used for an individual field.

AlternatingItemTemplate

The template used for alternate rows.

EditItemTemplate

The template used when the row is being
edited.

HeaderTemplate

The templat
e used for the header row.

FooterTemplate

The template used for the footer row.

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
50

A template field that includes a validation control

<asp:TemplateField HeaderText="ID">

<ItemTemplate>

<asp:Label ID="lblGridCategory" runat="server"

Text='<%# Bind("CategoryID") %>
'></asp:Label>

</ItemTemplate>

<EditItemTemplate>

<asp:TextBox ID="txtGridCategory" runat="server"

Text='<%# Bind("CategoryID") %>'></asp:TextBox>

<asp:RequiredFieldValidator runat="server"

ID="RequiredField
Validator4"

ControlToValidate="txtGridCategory"

ErrorMessage="ID is a required field."

ValidationGroup="Edit">*


</asp:RequiredFieldValidator>

</EditItemTemplate>

<HeaderStyle HorizontalAlign="Left" />


<ItemStyle Width="100px" />

</asp:TemplateField>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
51

Category Maintenance
app.
with template fields

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
52

The Default.aspx file

<asp:GridView ID="GridView1" runat="server"

AutoGenerateColumns="False" DataKeyNames="CategoryID"

DataSourceID="SqlDataSource1" ForeColor="Black">

<Columns>

<asp:TemplateField HeaderText="ID">

<ItemTemp
late>

<asp:Label id="lblGridCategory"

runat="server"

Text='<%# Bind("CategoryID") %>'>

</asp:Label>

</ItemTemplate>

<EditItemTemplate>

<asp:Lab
el id="lblGridCategory"

runat="server"

Text='<%# Bind("CategoryID") %>'>

</asp:Label>

</EditItemTemplate>

<HeaderStyle HorizontalAlign="Left" />

<ItemStyle Width="
100px" />

</asp:TemplateField>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
53

The Default.aspx file (cont.)

<asp:TemplateField HeaderText="Short Name">

<ItemTemplate>

<asp:Label ID="lblGridShortName"

runat="server"

Text='<%# Bind("ShortName") %>'>


</asp:Label>

</ItemTemplate>

<EditItemTemplate>

<asp:TextBox ID="txtGridShortName"

runat="server" width = "125px"


MaxLength=
"
15
"

Text='<%# Bind("Sh
ortName") %>'>

</asp:TextBox>

<asp:RequiredFieldValidator

ID="RequiredFieldValidator5"

runat="server"

ControlToValidate="txtGridShortName"

Er
rorMessage=


"Short Name is a required field."


ForeColor=
"
White"
ValidationGroup="Edit">*

</asp:RequiredFieldValidator>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
54

The Default.aspx file (cont.)

</EditItemTemplate>

<HeaderStyle HorizontalAlign="Left" />

<ItemStyle Width="150px" />

</asp:TemplateField>

<asp:TemplateField HeaderText="Long Name">

<ItemTempla
te>

<asp:Label ID="lblGridLongName"

runat="server"

Text='<%# Bind("LongName") %>'>

</asp:Label>

</ItemTemplate>

<EditItemTemplate>

<asp:TextBox
ID="txtGridLongName"

runat="server" width = "180px"



MaxLength=
"
5
0
"

Text='<%# Bind("LongName") %>'>

</asp:TextBox>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
55

The Default.aspx file (cont.)

<asp:RequiredFieldValidator

ID="RequiredFieldValidator6"

runat="server"

ControlToValidate="txtGridLongName"

ErrorMessage=


"Long Name is a required field."


ForeColor=
"
White
"

ValidationGroup="Edit">*

</asp:RequiredFieldValidator>

</EditItemTemplate>

<HeaderStyle HorizontalAlign="Left" />


<ItemStyle Width="200px" />

</asp:TemplateField>

<asp:CommandField ButtonType="Button"

ShowEditButton="True"

CausesValidation="True"

ValidationGroup="Edit" />

<asp:CommandField ButtonType="Butto
n"

ShowDeleteButton="True"

CausesValidation="False" />

</Columns>

Murach’s ASP.NET 3.5/VB, C14

© 2008, Mike Murach & Associates, Inc.


Slide
56

The Default
.aspx file (cont.)

<HeaderStyle BackColor="Silver" Font
-
Bold="True"

ForeColor="White" />

<RowStyle BackColor="White" ForeColor="Black" />

<AlternatingRowStyle BackColor="WhiteSmoke"


ForeColor="Black" />

<EditRowStyle BackCo
lor="Blue" ForeColor="White" />

</asp:GridView>

.

.

.

<asp:ValidationSummary ID="ValidationSummary1"


runat="server"

HeaderText="Please correct the following errors:"


ValidationGroup="Edit"
/>

.

.

.