Online courses in ASP.NET MVC / Core, Angular, and Design Patterns. Read more...
Know the inner dimension of personal growth and well-being. A practical yogic approach to success, happiness, and inner transformation. A unique sequence of Mantra, Pranayama, Hand Mudras and Meditation. Conducted by Bipin Joshi in Thane. See more details here.

Validating data in GridView cont

Validating data in GridView control

Introduction

ASP.NET 2.0 GridView control allows us to quickly edit and delete records. However, most of the real world cases call for validating the data being edited or deleted. There can be several approaches taken for validating data. This article explores some of them viz.

  • Client side validation using validation controls
  • Server side validation using validation controls
  • Server side validation using GridView evemts

Creating the sample web form

For our example we are going to use Customers table of Northwind database. To begin with create a new web site using VS.NET. Drag and drop an SQL Data Source control on the web form. Open its smart tag and choose "Configure Data Source" option to start Configure Data Source wizard. On the first step of the wizard click on "New Connection" button to open a dialog as shown in Figure 1.

Enter the database details as per your setup and click on OK. On the next step select CustomerID, CompanyName, ContactName and Country columns (Figure 2).

Click on the "Advanced" button and check the "Generate INSERT, UPDATE and DELETE statements" checkbox (Figure 3).

Complete the wizard by clicking finish. Now that you have configured the SQL Data Source control let's bind it with a GridView control.

Drag and drop a GridView control on the web form. Open its smart tag and configure it as shown in Figure 4.

Here, we set the Data Source of the GridView to SqlDataSource1. This will add four BoundFields to the GridView. We also enable paging, sorting and editing features of the GridView.

Client side validation using validation controls

By default when the GridView controls goes in edit mode, it displays TextBoxes for entering values. You can not attach validation controls directly to these TextBoxes. We need to convert these BoundFields to TemplateFields. In order to do so select "Edit Columns..." from the smart tag of the GridView. This will open Fields dialog as shown in Figure 5.

Select CompanyName and ContactName fields and click on "Covert this field into a TemplateField" link. This will convert them from BoundField to TemplateField.

Now from the smart tag of the GridView choose "Edit Template" and then select "EditItemTemplate" of CompanyName column. This will display the template designer for the column as shown in Figure 6.

Next, drag and drop a RequiredFieldValidation control below the TextBox. Set the ControlToValidate property of RequiredFieldValidator control to TextBox1 (i.e. the ID of the TextBox). Also, set its ErrorMessage property to "Please enter company name". Note that by default all validation controls validate on the client side. Right click on the GridView and select "End template editing"

Run the web form. Click on the Edit button of the GridView so that it goes into the edit mode. Make CompanyName blank and click on Update button. You should see an error message as shown in Figure 7.

This way you can attach client side validation controls to the GridView columns.

Server side validation using validation controls

Let's proceed further by validating on the server side. We will use the CustomValidator control for this purpose. Just like we attached the RequiredFieldValidator control to the TextBox, attach a CustomValidator to the ContactName column. Set the ControlToValidate and Error message properties to the appropriate values.

Double click on the CustomValidator control to go into the ServerValidate event handler and write the following code in it.

protected void CustomValidator1_ServerValidate
(object source, ServerValidateEventArgs args)
{
if (args.Value.StartsWith("Mr.") || 
args.Value.StartsWith("Mrs.") || 
args.Value.StartsWith("Ms."))
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}

Here, our validation criteria is that the entered name must not contain title of courtesy (Mr./Mrs./Ms.). We check the value entered in the TextBox using args.Value property and if it starts with Mr. or Mrs. or Ms. we set the args.IsValid property to false.

If you run the web form and try entering wrong value in the ContactName column then you will see the error message displayed as before and the value will not be accepted by the GridView control.

Server side validation using GridView events

Up till now we used the validation controls to validate GridView input on client and server side. However, at times you many need more control and flexibility than that is provided by validation controls. That is when you can handle certain events of GridView control. Especially the following events are important for validation point of view.

  • RowUpdating
  • RowDeleting
  • PageIndexChanging
  • RowEditing
  • RowCancelingEdit

Out of these events RowUpdating and RowDeleting are possibly the most common ones. These events are raised before updating and deleting the record respectively.

In our example we will illustrate the use of Updating event for the validation purpose. Add GridView1_RowUpdating event handler as shown below:

protected void GridView1_RowUpdating
(object sender, GridViewUpdateEventArgs e)
{
if (e.NewValues["Country"]==null)
{
e.Cancel = true;
return;
}
if (e.NewValues["Country"].ToString() == "Bharat")
{
e.NewValues["Country"] = "India";
}
}

The RowUpdating event handler receives an event argument of type GridViewUpdateEventArgs. The GridViewUpdateEventArgs class has three important collections - OldValues, NewValues and Keys. The OleValues collection contains list of old column values, the NewValues collection contains the list of new values entered by the user and the Keys collection contains the list of primary key values as defined by DataKeyNames.

Inside the event handler we added two validation conditions:

  • If country is empty the entry must not be accepted
  • If the country entered is "Bharat" it should be saved as "India" for the sake of uniformity

We used the NewValues collection to check the entered country. If the country is null then we set Cancel property of GridViewUpdateEventArgs class to true. This tells GridView that the event handler should be cancelled. The NewValues collection is read/write collection and in the second if condition we set the Country to India.

Run the web form and try entering empty country. You will find that the data is not accepted by the GridView. Similarly if you set country to "Bharat" it gets replaced as "India".

Summary

In this article we learnt various ways of validating data in a GridView control. You can attach validation controls to the TemplateFields to perform client side or server side validation. If you need more control you can also handle RowUpdating or RowDeleting events of the GridView.




Bipin Joshi is a software consultant, an author and a yoga mentor having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Meditation to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 22 Apr 2006



Tags : ASP.NET Data Access Server Controls Data Controls