|
Total Views :
44098 |
|
Adding to your Favorites....
|
|
|
 |
|
|
|
|
|
Introduction |
This article explains the concept of integrating Asp.Net Validation Controls with
the GridView control dynamically(at run-time).
A GridView control is used to display records in the tabular fashion which also
provides the functionality to add new records, edit, update and delete the database
records. While editing the records in the GridView control, we have to validate
the data input by the user before it is saved into the database. The scope of this
article is not to explain the functionalities of GridView control or define every
validation controls in detail. Rather, we try to explain an easy way to integrate
the Asp.Net Validation controls with the GridView control dynamically that is at
run-time. Asp.Net got very rich validation controls which is listed below
1. RequiredFieldValidator
2. RangeValidator
3. RegularExpressionValidator
4. CompareValidator
5. CustomValidator
All the above validation controls can be created dynamically at run-time and integrate
with any Input controls.
|
|
|
|
|
Getting into the Topic
Drag and drop a GridView control into your webpage and set its AutoGenerateColumns
property as false. We are going to bind the GridView with the Customer Table from
the database. The columns in the customer table are Customer Code [Cus_Code], Customer
Name [Cus_Name], Gender [Cus_Sex], Age [Cus_Age], City [Cus_City] and Email Address
[Cus_Email]. Specify the DataKeyNames as Cus_Code. Add 5 BoundField columns into
the GridView and set its Data Field with the above column names. Add one CommandField
column, make its command type as Edit/Update. Now convert all the BoundField fields
in the GridView to TemplateField. So the every TemplateField will have a ItemTemplate
section and EditItemTemplate section. ItemTemplate section will have a Asp.Net Label
control binded to its corresponding column name. And EditItemTemplate section will
have a TextBox control which is also binded to its corresponding column name.
|
|
For Customer Name column, we are going to put a static RequiredFieldValidator control
at design time itself. So add a RequiredFieldValidator control into that column’s
EditItemTemplate section. Specity its ControlToValidate property as TextBox1 and
Error Message as “Name Required.”. For other columns such as Gender, we are going
to use CustomValidator, for Age column we use RangeValidator, for Email we use RegularExpressionValidator
and for City we use dynamic RequiredFieldValidator. Now the Html code of the GridView
will look as follows
|
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"
AutoGenerateColumns="False" DataKeyNames="Cus_Code" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Name" SortExpression="Cus_Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Cus_Name") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
ErrorMessage="Name Required"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Cus_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gender">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Cus_Sex") %>'
MaxLength="3" Width="50px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("Cus_Sex") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age" SortExpression="Cus_Age">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Cus_Age") %>'
MaxLength="3" Width="50px"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Cus_Age") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email" SortExpression="Cus_Email">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Cus_Email") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("Cus_Email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City" SortExpression="Cus_City">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("Cus_City") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Cus_City") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
|
|
Initialize the GridView control
Write a private method to fetch data from database as follows
|
private void BindGridView()
{
string sql = "Select * from CustomerTest Order By Cus_Name";
SqlDataAdapter da = new SqlDataAdapter(sql, “Yourconnectionstring”);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
} |
|
Call this method in the page load event of your webpage as follows
|
|
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
} |
|
Press F5, you can see the GridView loaded with data from your Customer
table. |
|
|
|
Enable GridView Edit and Cancel Events
In the RowEditing event of the GridView control, put the following
code.
|
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView();
} |
|
To
do cancel event, paste the following code in the RowCancelingEdit event.
|
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs
e)
{
GridView1.EditIndex = -1;
BindGridView();
} |
|
Hit F5 again, your GridView will be loaded with data from your Customer table, and
if you click the Edit linkbutton in any row, the corresponding row will change to
Edit mode. You can also cancel the Edit operation by clicking the Cancel linkbutton.
|
Towards the Goal
Now we are going to create validation control dynamically in the RowDataBound event
of the GridView control. First we are going to create a CustomValidator control
for the Gender column. CustomValidator is used to validate any user input in a customized
way either by a client-side validation script or a server-side validation script.
Here we go for the CustomValidator with client-side JavaScript validation. The condition
is the TextBox for the Gender column should accept value of single character either
M or F for Male and Female respectively. The server side code to create a CustomValidator
will be as follows
|
CustomValidator customValidator = new CustomValidator();
customValidator.ID = "CustomValidator1";
customValidator.ControlToValidate = "TextBox2";
customValidator.ErrorMessage = "Invalid Gender";
customValidator.SetFocusOnError = true;
customValidator.ValidateEmptyText = true;
customValidator.ClientValidationFunction = "fnClientFunction";
e.Row.Cells[1].Controls.Add(customValidator);
|
|
From the above code, we create an instance of CustomValidator class, we mention
an ID for it, and we specify the ControlToValidate to TextBox2, we specify the ErrorMessage
and set the SetFocusOnError and ValidateEmptyText property to true. Then we specify
a JavaScript function name in the ClientValidationFunction property. The JavaScript
function will be as follows
<script>
function fnClientFunction(source, arguments)
{
if (arguments.Value=="M" || arguments.Value=="F")
arguments.IsValid=true;
else
arguments.IsValid=false;
}
</script> |
|
|
|
The last line of the CustomValidator creation code is very important which binds,
incorporate or integrate the validation control at exact Row and Column of the GridView
control.
|
e.Row.Cells[1].Controls.Add(customValidator); |
All validation controls after creation has to be bind with the GridView control
in the above manner. Now let we go in fast track to create other validation controls
and bind it with the GridView.
|
|
|
RangeValidator for Age Field
RangeValidator validates the input to fall between the specified range of MinimumValue
and MaximumValue property. We can also mention the validation data type through
the Type property of the RangeValidator. The code for creating and binding a RangeValidator
with GridView control is as follows
|
RangeValidator rangevalidator = new RangeValidator();
rangevalidator.ID = "RangeValidator1";
rangevalidator.ControlToValidate = "TextBox3";
rangevalidator.ErrorMessage = "Invalid Age";
rangevalidator.MaximumValue = "100";
rangevalidator.MinimumValue = "0";
rangevalidator.SetFocusOnError = true;
rangevalidator.Type = ValidationDataType.Integer;
e.Row.Cells[2].Controls.Add(rangevalidator); |
|
RegularExpressionValidator for Email Column
RegularExpressionValidator, as the name suggests you can define your own Regular
Expressions and assign it to the ValidationExpression property. Here we use a Regular
Expression for the Email Addresses.
RegularExpressionValidator regexpvalidator = new RegularExpressionValidator();
regexpvalidator.ID = "RegularExpressionValidator1";
regexpvalidator.ValidationExpression = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
regexpvalidator.ControlToValidate = "TextBox4";
regexpvalidator.ErrorMessage = "Invalid Email Id";
regexpvalidator.SetFocusOnError = true;
e.Row.Cells[3].Controls.Add(regexpvalidator); |
RequiredFieldValidator for City column
RequiredFieldValidator used to mention the mandatory field or compulsory field.
It won’t allow you to leave the field empty. Below is the code to create RequiredFieldValidator
dynamically.
RequiredFieldValidator reqfldVal = new RequiredFieldValidator();
reqfldVal.ID = "RequiredValidator10";
reqfldVal.ControlToValidate = "TextBox5";
reqfldVal.ErrorMessage = "City Required";
reqfldVal.SetFocusOnError = true;
e.Row.Cells[4].Controls.Add(reqfldVal);
|
Complete Source Code to be added inside RowDataBound event of GridView
The full source code of the RowDataBound event is given below.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Checking EditIndex should be same as current Row Index, then bind the validation
controls in that particular row.
if (GridView1.EditIndex == e.Row.RowIndex)
{
CustomValidator customValidator = new CustomValidator();
customValidator.ID = "CustomValidator1";
customValidator.ClientValidationFunction = "fnClientFunction";
customValidator.ControlToValidate = "TextBox2";
customValidator.ErrorMessage = "Invalid Gender";
customValidator.SetFocusOnError = true;
customValidator.ValidateEmptyText = true;
e.Row.Cells[1].Controls.Add(customValidator);
RangeValidator rangevalidator = new RangeValidator();
rangevalidator.ID = "RangeValidator1";
rangevalidator.ControlToValidate = "TextBox3";
rangevalidator.ErrorMessage = "Invalid Age";
rangevalidator.MaximumValue = "100";
rangevalidator.MinimumValue = "0";
rangevalidator.SetFocusOnError = true;
rangevalidator.Type = ValidationDataType.Integer;
e.Row.Cells[2].Controls.Add(rangevalidator);
RegularExpressionValidator regexpvalidator = new RegularExpressionValidator();
regexpvalidator.ID = "RegularExpressionValidator1";
regexpvalidator.ValidationExpression = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
regexpvalidator.ControlToValidate = "TextBox4";
regexpvalidator.ErrorMessage = "Invalid Email Id";
regexpvalidator.SetFocusOnError = true;
e.Row.Cells[3].Controls.Add(regexpvalidator);
RequiredFieldValidator reqfldVal = new RequiredFieldValidator();
reqfldVal.ID = "RequiredValidator10";
reqfldVal.ControlToValidate = "TextBox5";
reqfldVal.ErrorMessage = "City Required";
reqfldVal.SetFocusOnError = true;
e.Row.Cells[4].Controls.Add(reqfldVal);
}
} |
|
Updating new Data in GridView
As usual we can update the changed data into the database Customer table in a very
custom way. So write you code in the RowUpdating event of the GridView control as
follows |
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox TextBox1 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[0].FindControl("TextBox1"));
TextBox TextBox2 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].FindControl("TextBox2"));
TextBox TextBox3 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].FindControl("TextBox3"));
TextBox TextBox4 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].FindControl("TextBox4"));
TextBox TextBox5 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].FindControl("TextBox5"));
string Age = "0";
if (TextBox3.Text.Trim() != String.Empty)
Age = TextBox3.Text;
string sql = "UPDATE Customers " + "SET Cus_Name='" + TextBox1.Text + "', Cus_Sex='"
+
TextBox2.Text + "', Cus_Age='" + Age + "', Cus_City='" + TextBox5.Text + "', Cus_Email='"
+
TextBox4.Text + "' " + "WHERE Cus_Code= " + GridView1.DataKeys[e.RowIndex].Value;
using (SqlConnection conn = new SqlConnection(“YourConnectionString”))
{
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
GridView1.EditIndex = -1;
BindGridView();
} |
|
That’s
it. We are right on job. Save and run your application. Click on the Edit
link, do all sorts of inputs you want, try to compromise the validation control.
If so, adjust your code accordingly. This sample illustrates a simple and easy way
to create validation control and bind it with GridView control dynamically at run-time.
Hope we achieve our targets.
|
|
Click here to view our GridView sample with dynamic Validation controls |
|
|
|
|
|
|
|
|