LogoASPAlliance: Articles, reviews, and samples for .NET Developers
ASP.NET 4.0 and the Entity Framework 4 - Part 5 - Using the GridView and the EntityDataSource
by Vince Varallo
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 39121/ 83


This article will demonstrate how to view and edit records in a table using the GridView, EntityDataSource, and Validator controls.  The article also demonstrates how to generate an ADO.NET Entity Data Model to update and delete records in a table.  At the end of this article you'll notice that there wasn't one line of code needed to edit the records in the table. 

This article uses the AdventureWorks sample database that can be downloaded from for SQL Server 2008.  Download and install the AdventureWorks2008_SR4.exe file.  The sample code is written using Visual Studio 2010.

The goal of this article is to create a web page that looks like the following image.

The user can click on the Edit link to change the value of the fields.  I'll show you how to complete a drop down list in the row when editing the Title and also how to use the RequiredFieldValidator and the RegularExpressionValidator controls to implement the business rules.  The complete code for this article can be downloaded here.

Step 1: Create the Web Site

1.    Launch Visual Studio 2010 and select FileàNewàWeb Site… from the menu.

2.    Click on the Visual C# templates and then select ASP.NET Empty Web Site.

3.    Select File System from the drop down list next to Web Location and change the name of the site to C:\...\Visual Studio 2010\Projects\GridViewSample and click the OK button.

4.    Visual Studio 2010 will create a web site with only a web.config file.

Step 2: Add an Entity Data Model

The next step is to create an entity modal using the new Entity Framework 4.  Once you have a modal you can then add EntityDataSource controls to you application that can dynamically query your database.

1.    Right click on the web site in the Solution Explorer and select Add New Item… from the pop-up menu.

2.    Select ADO.NET Entity Data Model from the list of templates.  Change the file name to AdventureWorksModel.edmx and click the Add button.  You'll get a message asking if you want to create an App_Code folder.

3.    Click Yes.  This will display the Entity Data Model Wizard.

4.    Choose Generate From Database and click the Next button.

5.    The next screen asks you to choose a data connection.  The drop down list will display any connections you have already setup in the Server Explorer.  If you haven't already created a connection to the AdventureWorks database then click the New Connection button.

6.    This displays the Connection Properties form.  Enter your server name, authentication information, and select the AdventureWorks database from the list of available databases.

7.    Click the Test Connection button to make sure you have entered the right information.  If you get an error fix the settings and try again.

8.    Once testing the connection is successful click the OK button.

9.    The AdventureWorks connection should appear in the list of connections and be selected.

10. Make sure the "Save entity connection settings in Web.Config as" checkbox is checked.

11. Click the Next button.

12. The next form in the wizard allows you to select which tables, views, or stored procedures you want to add to the model.  We're only going to be editing the Contact table so expand the Tables node and check the box next to the Contact table.

13. Click the Finish button.  Visual Studio will add the AdventureWorks entity data model to your web site.

Step 3: Create the Web Form

Now that you have and entity data model you can create a web form that will use this model.

1.    Right click on the web site in the Solution Explorer and select Add New Item… from the pop-up menu.

2.    Select Web Form from the list of templates and leave the name of the file set to Default.aspx.  click the Add button

3.    The Default.aspx web form will be added to your project and the markup is displayed.  Switch your view to Design mode.

4.    Expand the Data node in your toolbox and you should see the EntityDataSource control.  Drag this control onto your web form.  You can drop it anywhere on the form.

5.    Click the smart tag on the EntityDataSource control and select Configure Data Source from the pop-up menu.  The Configure Data Source wizard will appear.

6.    Choose AdventureWorksEntities from the list of Named Connections.  The DefaultContainerName will default to AdventureWorksEntities.  Click the Next button.

7.    Select Contacts for the EntitySetName and select Contacts for the EntityTypeFilter.

8.    Check the boxes to enable updates and deletes.

9.    Click the Finish button.

10. The entity data source is now configured so it can be bound to a GridView control.  Drag a GridView control onto the form.

11. Click the smart tag to display the pop-up menu next to the GridView if it doesn't appear by default.

12. Set the Choose Data Source list to EntityDataSource1.

13. Check the boxes next to Enable Paging, Enable Editing and Enable Deleting.

14. Click the Edit Columns… link from the pop-up menu.  You should see all of the fields listed in the Selected Fields list.

15. Click on the ContactID field and change its Visible property to False.  Do the same for the NameStyle, EmailPromotion, Phone, PasswordHash, PasswordSalt, AdditionalContactInfo, rowguid, and ModifiedDate fields.  Click the OK button.

16. Your web form should look like the following image.

17. Right click on the Default.aspx page and set it as the start up page.  Run your project by pressing F5.

18. You'll get a message asking if you want to modify the web.config file to enable debugging.  Click the OK button.

The web page should be displayed with the list of contacts in the table.  If you click on the Edit link each cell in that row will become a textbox and you'll be able to change the value.  To commit the changes to the database click the Update link.

Step 4: Create Template Fields

Let's say that your user didn't want to use a textbox to edit the Title.  Instead they want a drop down list to be displayed.  You can accomplish this by creating a Template field within the GridView control.  Stop your project and follow these steps to create a drop down list when editing the Title in the GridView control.

1.    Drag a second EntityDataSource control onto your web form.

2.    Click the smart tag and click on the Configure Data Source link.

3.    Select AdventureWorksEntities from the Named Connections list and click the Next button.

4.    Change the EntitySetName to Contacts. 

5.    Uncheck the Select All(Entity Value) checkbox and check the box next to the Title field.

6.    Click the Finish button.

7.    Click the Source View so you can see the markup.  You only want this control to select the distinct list of titles from the table and you want them to be ordered alphabetically.  You should see the following code in the markup view.

<asp:EntityDataSource ID="EntityDataSource2" runat="server" 
    DefaultContainerName="AdventureWorksEntities" EnableFlattening="False" 
    EntitySetName="Contacts" Select="it.[Title]">


8.    Change the Select attribute to

   Select="DISTINCT it.[Title]"

9.    Add the following attribute to order the records alphabetically.


10. The markup should look as follows:

<asp:EntityDataSource ID="EntityDataSource2" runat="server" 
    DefaultContainerName="AdventureWorksEntities" EnableFlattening="False" 
    EntitySetName="Contacts" Select="DISTINCT it.[Title]" OrderBy="it.[Title]">

11. Click back to Design view.

12. Click the smart tag on the GridView control and select Edit Columns… from the pop-up menu.

13. Click on the Title field in the Selected Fields list.

14. Click on the link above the OK button called "Convert this field into a TemplateField".

15. Now click the OK button.

16. Click the smart tag on the GridView control again and select Edit Templates from the pop-up menu.

17. The item template displays the controls displayed in the grid view when simply looking at the grid.  In this example the item template for the Title field is a label control.  The value of the title field will be displayed in the lable.

18. Click on the EditItemTemplate from the list.  This will allow you to change the control from a textbox to a drop down list.

19. Click on the textbox in the EditItemTemplate and delete it.

20. Drag a DropDownList control into the EditItemTemplate.

21. Click the smart tag next to the DropDownList control and select the Choose DataSource link.

22. Choose EntityDataSource2 from the Select a Data Source list.

23. Click the Refresh Schema link.  The Title field should be displayed in the drop down lists on the form.  Click the OK button.

24. This will populate the drop down list with the distinct list of values in the Title field from the table.  Now you have to configure the control to display the correct selected value based on the record you are editing.

25. Click the smart tag next to the DropDownList again.  Select Edit Data Bindings… from the pop-up menu.

26. The DataBinding form will appear.  In the Code Expression text box enter the text "Bind("Title")".  This will select the value in the drop down list based on the value of the title field of the selected record.

27. Click the OK button.

28. Run the project again and click on the Edit link of the first record.  You should see the DropDownList and the correct value selected.

Step 5: Add Validation

The last step is to add validation to editing the record.  For this example I'll show you how to validate that the last name is filled in and that the email address is in valid form.  Stop the project from running to return to design mode in Visual Studio 2010.

1.    Click the smart tag next to the GridView control again.  You're still in Edit Template mode and you need to exit this mode.  To exit this mode simply click on the End Template Editing link on the pop-up menu.

2.     You should see the GridView control again with the bound fields.  Click the smart tag and click Edit Columns… from the pop-up menu.

3.    Click the LastName field in the Selected Fields list and then click the Convert this field into a Template Field link.

4.    Do the same for the EmailAddress field.  Now click the OK button.

5.    Click the smart tag next to the GridView control again and select Edit Templates from the pop-up menu.

6.    Select the LastName EditItemTemplate from the list.

7.    Drag a RequiredFieldValidator control next to the textbox.

8.    Set the ControlToValidate property of the RequiredFieldValidator to Textbox1.

9.    Set the ForeColor property to Red.

10. Set the ErrorMessage property to Please enter a last name.

11. Click the smart tag next to the GridView control again.  Select the EmailAddress EditItemTemplate value from the list.

12. Drag a RegularExpressionValidator next to the textbox.

13. Set the ControlToValidate property to Textbox2.

14. Set the ForeColor property to Red.

15. Set the ErrorMessage property to Please enter a valid email address.

16. Click in the ValidationExpression property to display a the button with the ellipse.  Click this button.  This displays the list of standard expressions.  Select Internet e-mail address and click the OK button.

Now run the project again.  Click the edit link and blank out a name.  If you click the update button the validation message should appear.  If you take off the ".com" from the email address you should also see the email error message when you click Update.


This article demonstrated how to create an Entity Framework 4 model, use the EntityDataSource control to bind to a GridView control, use EditItemTemplates to customize editing a record, and also use the validation controls.  Notice there was not one line of code or SQL needed for the entire project.  The controls in Visual Studio 2010 really make it easy to develop web applications fast and are great for small applications.  However, there are many debates out there as to whether this is a good or a bad thing.  I'll let you decide that for yourself but at least you know the quick and dirty option exists and works fairly well.

Good luck on your project and happy coding.

Product Spotlight
Product Spotlight 

©Copyright 1998-2022  |  Page Processed at 2022-10-06 2:49:30 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search