Recipe 2.17. Editing Data in a GridView


Problem

You want to allow the user to edit the data within the table displayed by a GridView.

Solution

Add a GridView and an updateable data source, such as an asp:SqlDataSource, to the .aspx file, set the AutoGenerateEditButton attribute of the GridView control to true, add EditItemTemplate elements for each column that is to be editable, and initialize the properties of the data source in the code-behind.

In the .aspx file:

  • Add a GridView control where the data is to be displayed.

  • Add an asp:SqlDataSource.

  • Set the AutoGenerateEditButton attribute of the GridView to true.

  • Add EditItemTemplate elements for each editable column.

In the Page_Init event handler of the code-behind class for the page, use the .NET language of your choice to:

  • Initialize the SelectCommand property of the SqlDataSource to the SQL statement used to get the data to display from the database.

  • Initialize the UpdateCommand property of the SqlDataSource to the SQL statement used to update with parameters for the data the user can edit.

  • Add the parameters for the data the user can update to the UpdateParameters collection of the SqlDataSource.

  • Set the DataKeyNames collection of the SqlDataSource to the primary key(s) used to identify a unique row of data in the GridView.

Figure 2-17 shows the output of a typical example in normal mode and Figure 2-18 shows the output in edit mode. Examples 2-42, 2-43 through 2-44 show the .aspx file and the code-behind files for an application that produces this output.

Discussion

The GridView reduces the amount of custom code required for editing tabular data over what was required in ASP.NET 1.x (see Recipe 2.13). By binding a GridView to an updateable data source such as the SqlDataSource, the GridView's built-in editing capability can be used with little custom code.

Figure 2-17. GridView with editingnormal mode


Figure 2-18. GridView with editingrow edit mode


To add an edit button to each row in the GridView automatically, as shown in Figure 2-17, you need to set the AutoGenerateEditButton attribute to true. This will automatically generate the update and cancel buttons when the GridView is in edit mode (see Figure 2-18).

 <asp:GridView  runat="server" BorderColor="#000080" BorderWidth="2px" AutoGenerateColumns="False" HorizontalAlign="center" Width="90%" AutoGenerateEditButton="true" > 

If you use asp:BoundField elements to define the data displayed in the GridView, the GridView will automatically handle rendering textboxes for editing the data; however, you are limited to editing simple data. If you want to provide the ability for the user to select from a dropdown or provide any other special editing features, you will need to define the displayed data using an asp:TemplateField element for each editable column. The asp:TemplateField elements need to include an ItemTemplate element that defines how the data is to be displayed in normal mode and an EditItemTemplate element to define how the data is displayed in edit mode. The EditItemTemplates can include dropdowns, radio buttons, or any other control that your application needs.

 <Columns> <asp:BoundField DataField="SectionNumber" ItemStyle-HorizontalAlign="Center" HeaderText="Section" ReadOnly="True" /> <asp:TemplateField HeaderText="Section Heading" ItemStyle-HorizontalAlign="Left"> <ItemTemplate> <%#Eval("SectionHeading")%> </ItemTemplate> <EditItemTemplate> <asp:TextBox  runat="server" Columns="40" Text='<%# Bind("SectionHeading") %>' /> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="VB Example" ItemStyle-HorizontalAlign="Center"> <ItemTemplate> <%#yesNoSelections.Item(CInt(Eval("HasVBExample")))%> </ItemTemplate> <EditItemTemplate> <asp:DropDownList  runat="server" DataSource="<%# yesNoSelections %>" DataTextField="Text" DataValueField="Value" SelectedValue='<%# Bind("HasVBExample") %>' /> </EditItemTemplate> </asp:TemplateField> </Columns> 

In our example, we have two editable columns. The first column contains simple text. To provide more control over the size of the textbox displayed in edit mode, we have used an asp:TextBox and set the number of columns to 40.

The second column contains a yes/no value. We are using an asp:DropDownList control when the GridView is in edit mode to limit the choices the user can enter. In addition, we are binding the asp:DropDownList to an ArrayList containing the valid values (described later).

When using the GridView's built-in editing functionality with EditItemTemplates, the data binding must use the new Bind method instead of the Eval method. When using Bind and the form is posted back to the server, a name/value collection of the edited data is passed to the server and is used by ASP.NET to provide the parameter values for the update command.


The names of the parameters defined in the UpdateCommand and the UpdateParameters collection must match the names of the columns in the data source bound to the controls using the Bind method. If they do not match, the update will fail, indicating the missing parameter value must be specified. If you need the column names in the data source and parameter names to be different, you have to provide custom code to handle the differences.


In the Page_Init event handler in the code-behind, the ArrayListused to provide the valid selections in the asp:DropDownList displayed in edit modeis initialized. In our example, we created the list programmatically. In your application, the list can be created from a database or any other data source, as required.

The SqlDataSource is initialized in the normal manner with a couple of additions. The UpdateCommand property is set to the SQL required to update the data in the database. The SQL needs to use parameters for the values to update as well as the value of the primary key used to identify the unique record being updated.

 

dSource.UpdateCommand = "UPDATE EditProblem " & _ "SET SectionHeading=@SectionHeading" & _ ",HasVBExample=@HasVBExample" & _ " WHERE EditProblemID=@_EditProblemID"

dSource.UpdateCommand = "UPDATE EditProblem " + "SET SectionHeading=@SectionHeading" + ",HasCSExample=@HasCSExample" + " WHERE EditProblemID=@_EditProblemID";

In addition, Parameter objects need to be created and added to the UpdateParameters collection of SqlDataSource for each of the data values being changed. A Parameter object does not need to be added for the primary key value. ASP.NET will automatically handle the primary key value(s) from DataKeyNames collection (described below). The parameter names must match the names of the parameters in the SQL update statement.

 

param = New Parameter("SectionHeading", _ TypeCode.String) dSource.UpdateParameters.Add(param) param = New Parameter("HasVBExample", _ TypeCode.Int32) dSource.UpdateParameters.Add(param)

param = new Parameter("SectionHeading", TypeCode.String); dSource.UpdateParameters.Add(param); param = new Parameter("HasCSExample", TypeCode.Int32); dSource.UpdateParameters.Add(param);

The DataKeyNames collection is set to a string array containing the names of the column(s) used in the database as the primary key. This can be one or more columns.

 

Dim dataKeys(0) As String … dataKeys(0) = "EditProblemID" gvProblems.DataKeyNames = dataKeys

String[] dataKeys; … dataKeys = new string[1] {"EditProblemID"}; gvProblems.DataKeyNames = dataKeys;

Finally, the DataSourceID property is set to the ID of the SqlDataSource:

 

gvProblems.DataSourceID = dSource.ID

gvProblems.DataSourceID = dSource.ID;

The GridView's built-in editing will work only if the DataSourceID property of the GridView is set to the ID of the data source. If the DataSource property is used instead, you will have to implement all of the same event handlers required to perform editing with a DataGrid (see Recipe 2.13).


By using a GridView with an updateable data source and following the coding conventions for column and parameter names described in this recipe, editing can be implemented with a minimal amount of custom code.

The data source must be initialized in the Page_Init event handler. If the data source is initialized later in the page life cycle, ASP.NET will not have the information it needs to use the built-in editing functionality.


See Also

Recipe 2.13

Example 2-42. GridView with editing (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH02GridViewWithEditingVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH02GridViewWithEditingVB" Title="GridView With Editing" %> <asp:Content  Runat="server" ContentPlaceHolder> <div align="center" > GridView With Editing (VB) </div> <asp:SqlDataSource  runat="server" /> <asp:GridView  runat="server" BorderColor="#000080" BorderWidth="2px" AutoGenerateColumns="False" HorizontalAlign="center" Width="90%" AutoGenerateEditButton="true" > <HeaderStyle HorizontalAlign="Center" Css <RowStyle css /> <AlternatingRowStyle css /> <Columns> <asp:BoundField DataField="SectionNumber" ItemStyle-HorizontalAlign="Center" HeaderText="Section" ReadOnly="True" /> <asp:TemplateField HeaderText="Section Heading" ItemStyle-HorizontalAlign="Left"> <ItemTemplate> <%#Eval("SectionHeading")%> </ItemTemplate> <EditItemTemplate> <asp:TextBox  runat="server" Columns="40" Text='<%# Bind("SectionHeading") %>' /> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="VB Example" ItemStyle-HorizontalAlign="Center"> <ItemTemplate> <%#yesNoSelections.Item(CInt(Eval("HasVBExample")))%> </ItemTemplate> <EditItemTemplate> <asp:DropDownList  runat="server" DataSource="<%# yesNoSelections %>" DataTextField="Text" DataValueField="Value" SelectedValue='<%# Bind("HasVBExample") %>' /> </EditItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </asp:Content> 

Example 2-43. GridView with editing (.vb)

 Option Explicit On Option Strict On Imports Microsoft.VisualBasic Imports System.Configuration Imports System.Data Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' CH02GridViewWithEditingVB.aspx ''' </summary> Partial Class CH02GridViewWithEditingVB Inherits System.Web.UI.Page 'The following variable contains the list of yes/no selections used in 'the dropdown lists and is declared protected to provide access to the 'data from the aspx page Protected yesNoSelections As ArrayList '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page init event. It ''' is responsible for initializing the data source and the grid view ''' on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub Page_Init(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Init Dim dataKeys(0) As String Dim param As Parameter 'build the arraylist with the acceptable responses to the '"Has VB Sample" field yesNoSelections = New ArrayList(2) yesNoSelections.Add(New ListItem("No", "0")) yesNoSelections.Add(New ListItem("Yes", "1")) 'configure the data source to get the data from the database 'NOTE: This code must be executed anytime the page is rendered ' including postbacks dSource.ConnectionString = ConfigurationManager. _ ConnectionStrings("sqlConnectionString").ConnectionString dSource.DataSourceMode = SqlDataSourceMode.DataSet dSource.ProviderName = "System.Data.SqlClient" dSource.SelectCommand = "SELECT EditProblemID, SectionNumber" & _ ", SectionHeading, HasVBExample" & _ " FROM EditProblem" & _ " ORDER BY SectionNumber" dSource.UpdateCommand = "UPDATE EditProblem " & _ "SET SectionHeading=@SectionHeading" & _ ",HasVBExample=@HasVBExample" & _ " WHERE EditProblemID=@_EditProblemID" param = New Parameter("SectionHeading", _ TypeCode.String) dSource.UpdateParameters.Add(param) param = New Parameter("HasVBExample", _ TypeCode.Int32) dSource.UpdateParameters.Add(param) 'set the source of the data and the data keys for the gridview control dataKeys(0) = "EditProblemID" gvProblems.DataKeyNames = dataKeys gvProblems.DataSourceID = dSource.ID End Sub 'Page_Init End Class 'CH02GridViewWithEditingVB End Namespace 

Example 2-44. GridView with editing (.cs)

 using System; using System.Collections; using System.Configuration; using System.Data; using System.Web.UI.WebControls; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// CH02GridViewWithEditingCS.aspx /// </summary> public partial class CH02GridViewWithEditingCS : System.Web.UI.Page { // The following variable contains the list of yes/no selections used in // the dropdown lists and is declared protected to provide access to the // data from the aspx page protected ArrayList yesNoSelections; ///*********************************************************************** /// <summary> /// This routine provides the event handler for the page init event. It /// is responsible for initializing the data source and the grid view /// on the page. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void Page_Init(object sender, EventArgs e) { String[] dataKeys; Parameter param; // build the arraylist with the acceptable responses to the // "Has C# Sample" field yesNoSelections = new ArrayList(2); yesNoSelections.Add(new ListItem("No", "0")); yesNoSelections.Add(new ListItem("Yes", "1")); // configure the data source to get the data from the database // NOTE: This code must be executed anytime the page is rendered // including postbacks dSource.ConnectionString = ConfigurationManager. ConnectionStrings["sqlConnectionString"].ConnectionString; dSource.DataSourceMode = SqlDataSourceMode.DataSet; dSource.ProviderName = "System.Data.SqlClient"; dSource.SelectCommand = "SELECT EditProblemID, SectionNumber" + ", SectionHeading, HasCSExample" + " FROM EditProblem" + " ORDER BY SectionNumber"; dSource.UpdateCommand = "UPDATE EditProblem " + "SET SectionHeading=@SectionHeading" + ",HasCSExample=@HasCSExample" + " WHERE EditProblemID=@_EditProblemID"; param = new Parameter("SectionHeading", TypeCode.String); dSource.UpdateParameters.Add(param); param = new Parameter("HasCSExample", TypeCode.Int32); dSource.UpdateParameters.Add(param); // set the source of the data and the data keys for the gridview control dataKeys = new string[1] {"EditProblemID"}; gvProblems.DataKeyNames = dataKeys; gvProblems.DataSourceID = dSource.ID; } // Page_Init } // CH02GridViewWithEditingCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net