22
1 GridView Examples for ASP.NET 2.0: Editing the Underlying Data in a GridView In addition to deleting a GridView's underlying data, another common need is to allow end users to edit the data displayed in a GridView. With ASP.NET 1.x's DataGrid control, editing the data is certainly possible, but requires creating three event handlers and writing a dozen or so lines of code. With the GridView and ASP.NET 2.0, it is possible to create an editable GridView without writing a single line of code! All of the necessary functionality is encapsulated within the GridView. The GridView allows editing on a row-by-row basis. An editable GridView contains an additional column with an Edit button in each row. When the end user clicks on an Edit button that row becomes editable, causing the Edit button to change to Update and Cancel buttons and the other columns to become TextBoxes. The end user can then update one or more column values and click Update to save their changes. In this section we'll examine four examples. Our first demo will look at how to create an editable GridView whose data comes from a SqlDataSource. Next, we'll see how to create an editable GridView from an ObjectDataSource. As you may have guessed, when creating an editable GridView whose data comes from an ObjectDataSource, the underlying data access layer class must provide an appropriate Update method. We'll look at the required signature for the Update method and see how to configure the ObjectDataSource to use this method. In the last two demos we'll see how to customize the editing interface for a GridView column. By default, the TextBoxes have no validation controls associated with them, but your business rules might require certain validation. A particular field may be required or might need to be entered in a specific format. Additionally, the standard TextBox as an editing interface might not be acceptable; we'll also look at an example that replaces the TextBox with a databound DropDownList. Editing GridView Data That Comes From a SqlDataSource Creating an editable GridView whose data comes from a SqlDataSource is amazingly easy. To start, the GridView's SqlDataSource must contain an UpdateCommand with appropriate parameters. As we saw in the Deleting a GridView's Underlying Data section, creating such a SqlDataSource is as simple as checking the Generate Insert, Update, and Delete Statements from the dialog box shown back in Figure 35. (Recall that this dialog box is accessed through the second step of the SqlDataSource wizard, by clicking the Advanced button.) As with the delete example, checking the Generate Insert, Update, and Delete Statements will create not only an UPDATE statement, but INSERT and DELETE statements as well. These can be safely removed if you are creating a GridView that's limited to just editing the existing data. Once you have configured a SqlDataSource with an UPDATE statement, creating an editable GridView

GridView Examples for ASP_Net C#

Embed Size (px)

DESCRIPTION

Examples Gridview ASP.NET

Citation preview

Page 1: GridView Examples for ASP_Net C#

1

GridView Examples for ASP.NET 2.0: Editing the Underlying

Data in a GridView

In addition to deleting a GridView's underlying data, another common need is to allow

end users to edit the data displayed in a GridView. With ASP.NET 1.x's DataGrid

control, editing the data is certainly possible, but requires creating three event handlers

and writing a dozen or so lines of code. With the GridView and ASP.NET 2.0, it is

possible to create an editable GridView without writing a single line of code! All of the

necessary functionality is encapsulated within the GridView.

The GridView allows editing on a row-by-row basis. An editable GridView contains an additional column with an Edit button in each row. When the end user clicks on an Edit button that row becomes editable, causing the Edit button to change to Update and Cancel buttons and the other columns to become TextBoxes. The end user can then update one or more column values and click Update to save their changes.

In this section we'll examine four examples. Our first demo will look at how to create an editable GridView whose data comes from a SqlDataSource. Next, we'll see how to create an editable GridView from an ObjectDataSource. As you may have guessed, when creating an editable GridView whose data comes from an ObjectDataSource, the underlying data access layer class must provide an appropriate Update method. We'll look at the required signature for the Update method and see how to configure the ObjectDataSource to use this method. In the last two demos we'll see how to customize the editing interface for a GridView column. By default, the TextBoxes have no validation controls associated with them, but your business rules might require certain validation. A particular field may be required or might need to be entered in a specific format. Additionally, the standard TextBox as an editing interface might not be acceptable; we'll also look at an example that replaces the TextBox with a databound DropDownList.

Editing GridView Data That Comes From a SqlDataSource Creating an editable GridView whose data comes from a SqlDataSource is amazingly easy. To start, the GridView's SqlDataSource must contain an UpdateCommand with appropriate parameters. As we saw in the Deleting a GridView's Underlying Data section, creating such a SqlDataSource is as simple as checking the Generate Insert, Update, and Delete Statements from the dialog box shown back in Figure 35. (Recall that this dialog box is accessed through the second step of the SqlDataSource wizard, by clicking the Advanced button.)

As with the delete example, checking the Generate Insert, Update, and Delete Statements will create not only an UPDATE statement, but INSERT and DELETE statements as well. These can be safely removed if you are creating a GridView that's limited to just editing the existing data. Once you have configured a SqlDataSource with an UPDATE statement, creating an editable GridView

Page 2: GridView Examples for ASP_Net C#

2

is a breeze. Just add a new GridView to the page and, from its Smart Tag, click the Enable Editing checkbox (see Figure 39). This will add a CommandField to the GridView with an Edit button.

[ http://msdn.microsoft.com/en-us/library/ms972948.gridview_fig39l(en-us,MSDN.10).gif ]

Figure 39 (Click on the graphic for a larger image)

That's all there is to it! Figures 40 and 41 show screenshots of the editable GridView in action. Figure 40 shows the GridView in its pre-editable state. Figure 41 shows the screen after an Edit button has been clicked; note that the clicked Edit button gives way to Update and Cancel buttons, while the columns in the editable row are rendered as TextBoxes.

Page 3: GridView Examples for ASP_Net C#

3

Figure 40

Figure 41

In Figure 41 notice how the ProductID column is not editable. As the ASP.NET page's declarative syntax below shows, you can mark a GridView column as non-editable by settings its ReadOnly property to True. When poking through the markup below, be sure to take note of the following:

Page 4: GridView Examples for ASP_Net C#

4

• The SqlDataSource contains an UpdateCommand property and an <UpdateParameters> section, which describes the required parameters in the UPDATE statement. If you forget to add this UpdateCommand to the SqlDataSource you will not be able to create an editable GridView.

• The <asp:Parameter> tags in the <UpdateParameters> section will, by default, convert blank strings entered into the GridView to NULLs. You can override this behavior by setting the ConvertEmptyStringToNull property to False for whatever parameters needed.

• The ProductID column is non-editable due to the ReadOnly="True" setting in the associated BoundField.

• This example demonstrates the GridView's default editing interface, which renders all editable columns as TextBoxes.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">

</script>

<html >

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

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

<div>

<asp:SqlDataSource ID="productDataSource" R unat="server"

SelectCommand="SELECT [ProductName], [P roductID],

[UnitPrice], [UnitsInStock] FROM [Produ cts]"

UpdateCommand="UPDATE [Products] SET [P roductName] =

@ProductName, [UnitPrice] = @UnitPric e, [UnitsInStock] =

@UnitsInStock WHERE [ProductID] = @or iginal_ProductID"

ConnectionString="<%$ ConnectionStrings :NWConnectionString

%>">

<UpdateParameters>

<asp:Parameter Type="String"

Name="ProductName"></asp:Paramete r>

<asp:Parameter Type="Decimal"

Name="UnitPrice"></asp:Parameter>

<asp:Parameter Type="Int16"

Name="UnitsInStock"></asp:Paramet er>

<asp:Parameter Type="Int32"

Name="ProductID"></asp:Parameter>

</UpdateParameters>

</asp:SqlDataSource>

Page 5: GridView Examples for ASP_Net C#

5

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

DataSourceID="productDataSource" DataKe yNames="ProductID"

AutoGenerateColumns="False" AllowPaging ="True"

BorderWidth="1px" BackColor="White"

CellPadding="4" BorderStyle="None" Bord erColor="#3366CC">

<FooterStyle ForeColor="#003399"

BackColor="#99CCCC"></FooterStyle>

<PagerStyle ForeColor="#003399" Horizon talAlign="Left"

BackColor="#99CCCC"></PagerStyle>

<HeaderStyle ForeColor="#CCCCFF" Font-B old="True"

BackColor="#003399"></HeaderStyle>

<Columns>

<asp:CommandField

ShowEditButton="True"></asp:CommandField>

<asp:BoundField ReadOnly="True" Hea derText="ProductID"

InsertVisible="False" DataField ="ProductID"

SortExpression="ProductID"></as p:BoundField>

<asp:BoundField HeaderText="Product "

DataField="ProductName"

SortExpression="ProductName"></ asp:BoundField>

<asp:BoundField HeaderText="Unit Pr ice"

DataField="UnitPrice" SortExpre ssion="UnitPrice">

<ItemStyle HorizontalAlign="Rig ht"></ItemStyle>

</asp:BoundField>

<asp:BoundField HeaderText="Units I n Stock"

DataField="UnitsInStock"

SortExpression="UnitsInStock">

<ItemStyle HorizontalAlign="Rig ht"></ItemStyle>

</asp:BoundField>

</Columns>

<SelectedRowStyle ForeColor="#CCFF99" F ont-Bold="True"

BackColor="#009999"></SelectedRowSt yle>

<RowStyle ForeColor="#003399"

BackColor="White"></RowStyle>

</asp:GridView>

</div>

</form>

</body>

</html>

The above example was created without checking the Use optimistic concurrency checkbox. If you checked that along with the Generate Insert, Update, and Delete Statements checkbox, the UpdateCommand for the SqlDataSource would have included a more thorough WHERE clause.

Page 6: GridView Examples for ASP_Net C#

6

Instead of just using WHERE [ProductID] = @original_ProductID, with optimistic concurrency the WHERE clause would have read:

WHERE [ProductID] = @original_ProductID AND [Produc tName] =

@original_ProductName AND [UnitPrice] = @original _UnitPrice AND

[UnitsInStock] = @original_UnitsInStock

This would prevent an UPDATE from happening if, between the time the user clicked a GridView row's Edit button and having clicked the Update button, another user had modified that particular row.

Editing GridView Data That Comes from an ObjectDataSource Like deleting data from a GridView bound to an ObjectDataSource, creating an editable GridView bound to an ObjectDataSource requires very few changes in the creation of the ASP.NET page. Most of the work is required in adding a method to the data access layer class to handle the update. As with the Delete example, the signature for the Update method depends on the ObjectDataSource's ConflictDetection property. If you are using the default behavior—OverwriteChanges—then the Update method needs to accept the original primary key field(s) along with parameters for the non-primary key updated values. If, on the other hand, CompareAllValues is used, the Update method must accept both the updated and original non-primary key field values along with the original primary key field(s). To help clarify any confusion, let's look at a concrete example. Let's create a GridView that displays fields from the Northwind Products table, just like we did in the previous demo. For this demo, though, we'll need to add an Update method to the ProductDAL class. (Recall that we created the ProductDAL class back in the Accessing Data with the DataSource Controls section when examining the ObjectDataSource.) Assuming that we're using the OverwriteChanges behavior, the Update method would look like:

The UpdateProduct Method (Visual Basic)

Public Class ProductDAL

...

Public Shared Sub UpdateProduct(ByVal original_ ProductID As

Integer, _

ByVal productName As String, ByVal unitPrice As Decimal, _

ByVal unitsInStock As Integer)

'Updates the Products table

Dim sql As String = "UPDATE Products SET Pr oductName = " & _

" @ProductName, UnitPrice = @UnitPrice, U nitsInStock = " & _

"@UnitsInStock WHERE ProductID = @Product ID"

Using myConnection As _

New SqlConnection( _

ConfigurationManager.ConnectionStrings("NWConnectio nString").Connectio

nString)

Page 7: GridView Examples for ASP_Net C#

7

Dim myCommand As New SqlCommand(sql, my Connection)

myCommand.Parameters.Add( _

New SqlParameter("@ProductName", produ ctName))

myCommand.Parameters.Add(New SqlParamet er("@UnitPrice", _

unitPrice))

myCommand.Parameters.Add(New SqlParamet er("@UnitsInStock",

_

unitsInStock))

myCommand.Parameters.Add(New SqlParamet er("@ProductID", _

original_ProductID))

myConnection.Open()

myCommand.ExecuteNonQuery()

myConnection.Close()

End Using

End Sub

End Class

The UpdateProduct Method (C#)

public class ProductDAL

{

...

public static void UpdateProduct(int original_P roductID,

string productName, decimal unitPrice, int un itsInStock)

{

// Updates the Products table

string sql = "UPDATE Products SET ProductNa me = " +

"@ProductName, UnitPrice = @UnitPrice, U nitsInStock = " +

"@UnitsInStock WHERE ProductID = @Produc tID";

using (SqlConnection myConnection =

new

SqlConnection(ConfigurationManager.ConnectionString s["NWConnectionStri

ng"].ConnectionString))

{

SqlCommand myCommand = new SqlCommand(s ql, myConnection);

myCommand.Parameters.Add(new SqlParamet er("@ProductName",

productName));

myCommand.Parameters.Add(new SqlParamet er("@UnitPrice",

unitPrice));

myCommand.Parameters.Add(new SqlParamet er("@UnitsInStock",

unitsInStock));

myCommand.Parameters.Add(new SqlParamet er("@ProductID",

original_ProductID));

myConnection.Open();

myCommand.ExecuteNonQuery();

Page 8: GridView Examples for ASP_Net C#

8

myConnection.Close();

}

}

}

As you can see, the Update method, UpdateProducts(), takes in the original_ProductID along with each of the editable columns in the GridView: productName, unitPrice, and unitsInStock. If you had configured the ObjectDataSource to CompareAllValues you'd need an Update method with a signature like:

' Visual Basic .NET

Public Shared Sub UpdateProduct(ByVal original_Prod uctID as Integer, _

ByVal original_productName as String, _

ByVal decimal original_unitPrice as Decimal, _

ByVal original_unitsInStock as Integer, _

ByVal productName as String, ByVal unitPrice as D ecimal, _

ByVal unitsInStock as Integer)

...

End Sub

// C#

public static void UpdateProduct(int original_Produ ctID,

string original_productName, decimal original_uni tPrice,

int original_unitsInStock, string productName, de cimal unitPrice,

int unitsInStock)

{

...

}

If you use the CompareAllValues approach, it is your responsibility as the DAL developer to take whatever steps are needed to determine if the underlying data has been during the user's edits and, if so, how to resolve the issue. Once the DAL class has been given an appropriate Update method, the final step is configuring the ObjectDataSource to utilize this Update method. To accomplish this, from the ObjectDataSource's wizard navigate to the UPDATE tab and select the appropriate method (see Figure 42).

Page 9: GridView Examples for ASP_Net C#

9

Figure 42

That's all there is to it! From the end user's perspective, updating a GridView that is bound to a SqlDataSource is no different than updating a GridView that is bound to an ObjectDataSource. You can refer back to Figures 40 and 41 to see the editable GridView in action. The following shows the declarative syntax for the ASP.NET page. As with the SqlDataSource example, note that there's no code necessary in the ASP.NET page.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">

</script>

<html >

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

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

<div>

<asp:ObjectDataSource ID="productDataSource "

Runat="server" TypeName="ProductDAL"

SelectMethod="GetProducts" EnablePaging ="True"

SelectCountMethod="TotalNumberOfProduct s"

UpdateMethod="UpdateProduct">

<UpdateParameters>

Page 10: GridView Examples for ASP_Net C#

10

<asp:Parameter Type="Int32"

Name="ProductID"></asp:Parameter>

<asp:Parameter Type="String"

Name="productName"></asp:Paramete r>

<asp:Parameter Type="Decimal"

Name="unitPrice"></asp:Parameter>

<asp:Parameter Type="Int32"

Name="unitsInStock"></asp:Paramet er>

</UpdateParameters>

</asp:ObjectDataSource>

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

DataSourceID="productDataSource"

DataKeyNames="ProductID"

AutoGenerateColumns="False" AllowPaging ="True"

BorderWidth="1px" BackColor="White"

CellPadding="4" BorderStyle="None" Bord erColor="#3366CC">

<FooterStyle ForeColor="#003399"

BackColor="#99CCCC"></FooterStyle>

<PagerStyle ForeColor="#003399" Horizon talAlign="Left"

BackColor="#99CCCC"></PagerStyle>

<HeaderStyle ForeColor="#CCCCFF" Font-B old="True"

BackColor="#003399"></HeaderStyle>

<Columns>

<asp:CommandField

ShowEditButton="True"></asp:CommandField>

<asp:BoundField ReadOnly="True"

HeaderText="ProductID" InsertVis ible="False"

DataField="ProductID"

SortExpression="ProductID"></as p:BoundField>

<asp:BoundField HeaderText="Product "

DataField="ProductName" SortExpression="ProductName "></asp:BoundField>

<asp:BoundField HeaderText="Unit Pr ice"

DataField="UnitPrice" SortExpres sion="UnitPrice">

<ItemStyle HorizontalAlign="Rig ht"></ItemStyle>

</asp:BoundField>

<asp:BoundField HeaderText="Units I n Stock"

DataField="UnitsInStock"

SortExpression="UnitsInStock">

<ItemStyle HorizontalAlign="Rig ht"></ItemStyle>

</asp:BoundField>

</Columns>

<SelectedRowStyle ForeColor="#CCFF99" F ont-Bold="True"

BackColor="#009999"></SelectedRowSty le>

Page 11: GridView Examples for ASP_Net C#

11

<RowStyle ForeColor="#003399"

BackColor="White"></RowStyle>

</asp:GridView>

</div>

</form>

</body>

</html>

Customizing the Editing Interface The past two examples illustrate how easy it is to create an editable GridView. One disadvantage of the default editing capabilities of the GridView, though, is that the editing interface is likely suboptimal. By default, all editable columns in the editable GridView row are rendered as TextBoxes, and none of them have any sort of validation logic associated with them. In real-world situations, though, oftentimes we'll need to add validation logic to the editable inputs, or perhaps even use editing controls other than the TextBox.

Regardless of how you want to alter the GridView's editing interface, the way it's accomplished is through using TemplateFields as opposed to BoundFields. A BoundField will always display a TextBox in edit mode. With a TemplateField, however, you can specify precisely how the editing interface should function.

In this section we'll look at two examples of customizing the GridView's editing interface. In the first, we'll see how to add validation controls; in the second, we'll look at replacing the standard TextBox with a DropDownList instead.

Adding Validation Controls to the Editing Interface

Since the GridView's default editing interface does not provide any validation logic, an end user can enter any sort of data into the editable row's TextBoxes. Looking back at our last two editable GridView examples, consider what would happen if the user entered a value of, say, Sam for the Unit Price of a product. Such actions would result in an exception, since the database cannot set a decimal field to a string value. Similarly, we might want to impose certain business rules, such as the Unit Price is greater than 0, or that Product Name is a required field.

The GridView's editing interface can be manipulated on a column-by-column level. This is accomplished by using TemplateFields in place of BoundFields, and specifying the editable interface to be used. Let's examine how this is done by tweaking the earlier editable GridView bound to a SqlDataSource example to utilize validation controls in the Product, Unit Price, and Units In Stock columns.

The first step is to transform those three columns into TemplateFields. The simplest way to do this it to go to the Design view and click the Edit Columns link in the GridView's Smart Tag. Selecting a BoundField from the column list in the bottom left hand corner, you will see a Convert this field into a TemplateField link (see Figure 43). Go ahead and turn the Product, Unit Price, and Units In Stock columns into TemplateFields.

Page 12: GridView Examples for ASP_Net C#

12

Figure 43

As we saw earlier, when a GridView row is made editable, the BoundFields turn into TextBoxes. The TemplateFields, on the other hand, render whatever HTML markup and Web control syntax you specify in the TemplateField's EditItemTemplate. To edit a TemplateField's EditItemTemplate, choose the Edit Templates link from the GridView's Smart Tag. This will allow you to select what Template for what column you want to edit.

Note If a TemplateField lacks an EditItemTemplate the GridView column will be non-editable.

Notice that by converting the BoundFields into TemplateFields through the Design view, the TemplateField will contain an EditItemTemplate with a TextBox. Figure 44 shows editing the Product column's EditItemTemplate. The TextBox present was not added by myself, but placed there automatically when converting to the TemplateField.

Page 13: GridView Examples for ASP_Net C#

13

Figure 44

To add validation controls to an EditItemTemplate, simply drag and drop the appropriate validation controls from the Toolbox into the EditItemTemplate. Let's add a RequiredFieldValidator in the Product EditItemTemplate, and CompareValidators in the Unit Price and Units In Stock columns to ensure that the data entered is of the right type. Finally, add a ValidationSummary control to the page to display information about invalid data to the user.

Once you have added the validation controls your ASP.NET page's declarative syntax should look similar to the following:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">

</script>

<html >

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

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

<div>

<asp:SqlDataSource ID="productDataSourc e"

Runat="server"

ConnectionString="<%$ ConnectionStrings:NWConnecti onString %>"

Page 14: GridView Examples for ASP_Net C#

14

UpdateCommand="UPDATE [Products] SE T [ProductName] =

@ProductName, [UnitPrice] = @UnitPrice,

[UnitsInStock] = @UnitsInStock WHERE [ProductID] =

@original_ProductID"

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

[UnitPrice], [UnitsInStock] FROM [Products]">

<UpdateParameters>

<asp:Parameter Type="String"

Name="ProductName"></asp:Param eter>

<asp:Parameter Type="Decimal"

Name="UnitPrice"></asp:Parame ter>

<asp:Parameter Type="Int16"

Name="UnitsInStock"></asp:Par ameter>

<asp:Parameter Type="Int32"

Name="ProductID"></asp:Parame ter>

</UpdateParameters>

</asp:SqlDataSource>

<asp:GridView ID="GridView1" Runat="ser ver"

BorderColor="#3366CC" BorderStyle=" None"

CellPadding="4" BackColor="White"

BorderWidth="1px" AllowPaging="Tru e"

AutoGenerateColumns="False"

DataKeyNames="ProductID"

DataSourceID="productDataSource">

<FooterStyle ForeColor="#003399"

BackColor="#99CCCC"></FooterS tyle>

<PagerStyle ForeColor="#003399" Hor izontalAlign="Left"

BackColor="#99CCCC"></PagerS tyle>

<HeaderStyle ForeColor="#CCCCFF"

Font-Bold="True" BackColor="#0033 99"></HeaderStyle>

<Columns>

<asp:CommandField

ShowEditButton="True"></asp: CommandField>

<asp:BoundField ReadOnly="True"

HeaderText="ProductID" Inser tVisible="False"

DataField="ProductID"

SortExpression="ProductID"> </asp:BoundField>

<asp:TemplateField SortExpressi on="ProductName"

HeaderText="Product"><EditIte mTemplate>

<asp:TextBox ID="editProduc tName"

Runat="server"

Text='<%# Bind("ProductNam e")

%>'></asp:TextBox>

<asp:RequiredFieldValidator

Page 15: GridView Examples for ASP_Net C#

15

ID="RequiredFieldValidato r1"

Runat="server"

ErrorMessage="You must provi de a Product Name."

ControlToValidate="edit ProductName">

*</asp:RequiredFieldVal idator>

</EditItemTemplate>

<ItemTemplate>

<asp:Label Runat="serve r"

Text='<%# Bind("ProductNam e") %>'

ID="Label3"></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField SortExpressi on="UnitPrice"

HeaderText="Unit Price"><Edit ItemTemplate>

<asp:TextBox ID="editUnitPr ice" Runat="server"

Text='<%# Bind("UnitPrice ", "{0:#,##0.00}")

%>'

Columns="6"></asp:TextBox >

<asp:CompareValidator ID="C ompareValidator1"

Runat="server"

ErrorMessage="You must provide a valid currency val ue for the Unit

Price."

ControlToValidate="edit UnitPrice"

Operator="DataTypeCheck" Type="C urrency">

*</asp:CompareValidator >

</EditItemTemplate>

<ItemStyle

HorizontalAlign="Right"></ItemStyle>

<ItemTemplate>

<asp:Label Runat="serve r"

Text='<%# Bind("UnitPrice", "{0:c}") %>'

ID="Label1"></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField SortExpressi on="UnitsInStock"

HeaderText="Units In Stock"><E ditItemTemplate>

<asp:TextBox ID="editUnitsI nStock"

Runat="server"

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

Columns="4"></asp:TextB ox>

<asp:CompareValidator ID="C ompareValidator2"

Runat="server"

ErrorMessage="You must provide a valid integer for Units In Stock."

ControlToValidate="edit UnitsInStock"

Page 16: GridView Examples for ASP_Net C#

16

Operator="DataTypeCheck " Type="Integer">

*</asp:CompareValidator >

</EditItemTemplate>

<ItemStyle

HorizontalAlign="Right"></ItemStyle>

<ItemTemplate>

<asp:Label Runat="serve r"

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

ID="Label2"></asp:Label>

</ItemTemplate>

</asp:TemplateField>

</Columns>

<SelectedRowStyle ForeColor="#CCFF9 9"

Font-Bold="True"

BackColor="#009999"></SelectedRo wStyle>

<RowStyle ForeColor="#003399"

BackColor="White"></RowStyle>

</asp:GridView>

</div>

<div>

<asp:ValidationSummary ID="ValidationSummar y1" Runat="server"

/>

</div>

</form>

</body>

</html>

When editing a GridView row you may be wondering how the TextBox is populated with the correct field value for the editable row. As you can see in the TextBox Web control's declarative syntax, the magic is in the Bind() method. Setting the TextBox's Text property to <%# Bind(fieldName) %> displays the value of the field fieldName in the TextBox. This same syntax is also used in the Label Web controls in the TemplateFields' ItemTemplates.

Figure 45 shows a screenshot of the enhanced editable GridView. Note that if invalid values are entered into the fields the underlying data is not updated and the validation summary at the bottom of the GridView indicates what problems exist.

Page 17: GridView Examples for ASP_Net C#

17

[ http://msdn.microsoft.com/en-us/library/ms972948.gridview_fig45l(en-us,MSDN.10).gif ]

Figure 45 (Click on the graphic for a larger image)

Using an Alternative Web Control for the Editing Interface

For certain scenarios the TextBox might not be the ideal editing interface. For example, when editing a date field, users will be less prone to error selecting the date using a Calendar Web control, rather than having to type in the date in a TextBox. Similarly, for lookup data—data that is restricted to a set of legal values, which are commonly defined in a separate database table—the best editing interface is typically a DropDownList.

The Northwind database's Products table contains a CategoryID field that associates a product with a category from the Categories table. This is a prime case where a DropDownList would be suited for the editing interface. Modifying the editing interface to provide a DropDownList is remarkably easy, requiring no source code at all.

To start, create a SqlDataSource that's configured to return a list of products along with the products' associated categories. To accomplish this you'll need to use a custom SQL SELECT statement in the DataSource wizard, one that uses a join to retrieve the correct CategoryName for a product's CategoryID. The SQL query should look something like:

SELECT dbo.Products.ProductID, dbo.Products.Product Name,

dbo.Products.CategoryID, dbo.Categories.Cate goryName

FROM dbo.Products

INNER JOIN dbo.Categories ON

Page 18: GridView Examples for ASP_Net C#

18

dbo.Products.CategoryID = dbo.Categories.Cate goryID

Remember when creating the SqlDataSource to include an UpdateCommand. If you forget to specify an UpdateCommand the GridView cannot be made editable.

Next, add a GridView, bind it to the SqlDataSource, and make it editable. Feel free to remove the ProductID and CategoryID columns from the GridView, leaving just the ProductName and CategoryName fields.

Our next task is to customize the editing interface for the CategoryName column so that it uses a DropDownList of categories as opposed to a TextBox. As we saw in the previous section, a TemplateField is needed to create a customized editing interface, so convert the CategoryName column into a TemplateField. Next, from the Design view, edit the CategoryName column's EditItemTemplate.

The CategoryName EditItemTemplate should contain a TextBox. Go ahead and remove this and add the necessary controls to have a DropDownList of the available categories. Simply drag and drop a SqlDataSource onto the page configured to select the CategoryID and CategoryName fields from the Categories table. Next, add a DropDownList to the EditItemTemplate and bind it to this SqlDataSource (see Figure 46).

Figure 46

Page 19: GridView Examples for ASP_Net C#

19

If you visit the ASP.NET page in a browser at this point, you'll find that when editing a row in the GridView the CategoryName column displays a DropDownList of all categories, but regardless of the row's category, the first category in the DropDownList is always the one selected. We need to improve our page so that when a row becomes editable, the DropDownList's SelectedValue is set to the row's CategoryID value. This can be accomplished using the Bind() method we saw in the previous example, as shown in the TemplateField's markup below:

<asp:TemplateField SortExpression="CategoryName"

HeaderText="CategoryName">

<EditItemTemplate>

<asp:DropDownList ID="DropDownList1" Runat= "server"

DataSourceID="categoryDataSource"

DataTextField="CategoryName" DataValueF ield="CategoryID"

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

</asp:DropDownList>

</EditItemTemplate>

<ItemTemplate>

<asp:Label Runat="server" Text='<%# Bind("Ca tegoryName") %>'

ID="Label1"></asp:Label>

</ItemTemplate>

</asp:TemplateField>

With this final addition—setting the DropDownList's SelectedValue='<%# Bind("CategoryID") %>—the example is complete. Figure 47 shows a screenshot of the GridView as it's being edited.

Page 20: GridView Examples for ASP_Net C#

20

Figure 47

The following shows the complete declarative syntax for the ASP.NET page. Note that this entire exercise was accomplished without writing a line of code.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">

</script>

<html >

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

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

<div>

<asp:SqlDataSource ID="productsDataSource"

Runat="server" SelectCommand="SELECT dbo. Products.ProductID,

dbo.Products.ProductName, dbo.Products.C ategoryID,

dbo.Categories.CategoryName FROM dbo.Products INNER JOIN

dbo.Categories ON

dbo.Products.CategoryID = dbo.Categories.CategoryI D"

UpdateCommand="UPDATE [Products] SET [P roductName] =

@ProductName, [CategoryID] = @CategoryID WHERE [Pro ductID] =

@original_ProductID"

ConnectionString="<%$ ConnectionStrings :NWConnectionString

%>">

<UpdateParameters>

<asp:Parameter Type="String"

Name="ProductName"></asp:Paramet er>

<asp:Parameter Type="Int32"

Name="CategoryID"></asp:Parameter>

<asp:Parameter

Name="original_ProductID"></asp:Parameter>

</UpdateParameters>

</asp:SqlDataSource>

<asp:SqlDataSource ID="categoryDataSource" Runat="server"

SelectCommand="SELECT [CategoryID], [Cat egoryName] FROM

[Categories] ORDER BY [CategoryName]"

ConnectionString="<%$ ConnectionStrings :NWConnectionString

%>">

</asp:SqlDataSource>

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

Page 21: GridView Examples for ASP_Net C#

21

DataSourceID="productsDataSource" DataK eyNames="ProductID"

AutoGenerateColumns="False" AllowPaging ="True"

BorderWidth="1px" BackColor="White"

CellPadding="3" BorderStyle="None" Bord erColor="#CCCCCC">

<FooterStyle ForeColor="#000066"

BackColor="White"></FooterStyle>

<PagerStyle ForeColor="#000066" Horizon talAlign="Left"

BackColor="White"></PagerStyle>

<HeaderStyle ForeColor="White" Font-Bol d="True"

BackColor="#006699"></HeaderStyle>

<Columns>

<asp:CommandField

ShowEditButton="True"></asp:CommandField>

<asp:BoundField ReadOnly="True" Hea derText="ProductID"

InsertVisible="False" DataField=" ProductID"

SortExpression="ProductID">

<ItemStyle HorizontalAlign="Cen ter"></ItemStyle>

</asp:BoundField>

<asp:BoundField HeaderText="Product Name"

DataField="ProductName"

SortExpression="ProductName"></as p:BoundField>

<asp:TemplateField SortExpression=" CategoryName"

HeaderText="CategoryName"><Edit ItemTemplate>

<asp:DropDownList ID="DropDownL ist1"

Runat="server"

DataSourceID="categoryDat aSource"

DataTextField="CategoryName "

DataValueField="CategoryID"

SelectedValue='<%# Bind("Categ oryID") %>'>

</asp:DropDownList>

</EditItemTemplate>

<ItemTemplate>

<asp:Label Runat="server"

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

ID="Label1"></asp:Label>

</ItemTemplate>

</asp:TemplateField>

</Columns>

<SelectedRowStyle ForeColor="White"

Font-Bold="True"

BackColor="#669999"></SelectedRowStyle>

<RowStyle ForeColor="#000066"></RowStyl e>

</asp:GridView>

</div>

Page 22: GridView Examples for ASP_Net C#

22

</form>

</body></html>