Integrating Asp.Net Validation Controls with GridView at run-time |
This tutorial 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 |
|
- RequiredFieldValidator
- RangeValidator
- RegularExpressionValidator
- CompareValidator
- CustomValidator
|
|
| 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="t1" runat="server" Text='<%# Bind("Cus_Name") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="t1" 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="t2" 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="t3" 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="t4" 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="t5" 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 |
login method: |
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();
}
} |
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();
} |
| |
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 = "t2";
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> |
| 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 = "t3";
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 regvalidator = newRegularExpressionValidator();
regvalidator.ID = "RegularExpressionValidator1";
regvalidator.ValidationExpression = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
regvalidator.ControlToValidate = "t4";
regvalidator.ErrorMessage = "Invalid Email Id";
regvalidator.SetFocusOnError = true;
e.Row.Cells[3].Controls.Add(regvalidator); |
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 = "t5";
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 = "t2";
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 = "t3";
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 = "t4";
regexpvalidator.ErrorMessage = "Invalid Email Id";
regexpvalidator.SetFocusOnError = true;
e.Row.Cells[3].Controls.Add(regexpvalidator);
RequiredFieldValidator reqfldVal = new RequiredFieldValidator();
reqfldVal.ID = "RequiredValidator10";
reqfldVal.ControlToValidate = "t5";
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 t1=(TextBox)GridView1.Rows[e.RowIndex].Cells[0].FindControl("t1"))
TextBox t2; = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].FindControl("t2")); TextBox t3 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].FindControl("t3"));
TextBox t4 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].FindControl("t4"));
TextBox t5 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].FindControl("t5"));
string Age = "0";
if (t3.Text.Trim() != String.Empty)
Age = t3.Text;
string sql = "UPDATE Customers " + "SET Cus_Name='" + t1.Text + "', Cus_Sex='" +
t2.Text + "', Cus_Age='" + Age + "', Cus_City='" + t5.Text + "', Cus_Email='" +
t4.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();
} |