News Ticker

Menu

Tạo RequiredFieldValidator động trong Asp.net

(Create Dynamic RequiredFieldValidator) - RequiredFieldValidator là Control được sử dụng để bắt yêu cầu nhập hay không nhập dữ liệu cho Textbox, Dropdownlist, FileUpload… trong Asp.net. Nhờ RequiredFieldValidator mà các lập trình viên dễ dàng trong việc xây dựng các Form nhập liệu. Tuy nhiên khi sử dụng RequiredFieldValidator lập trình viên thường để cứng việc kiểm soát các Control, chính việc này sẽ mất thời gian khi cần chuyển từ chế độ yêu cầu hoặc không yêu cầu nhập dữ liệu. Bài viết dưới đây sẽ hướng dẫn các bạn cách tạo Control RequiredFieldValidator động và tùy vào yêu cầu thực tế có thể dễ dàng thay đổi từ chế độ yêu cầu nhập liệu sang chế độ không nhập liệu hoặc ngược lại.

Xem những Video hay dành cho thiếu nhi - Nghe trên Youtube



Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET





B1: Tạo Project trong Microsoft Visual Studio 2010

- B2: Download thư viện bootstrap.css

- B3: Gắn file bootstrap.css vào file Site.Master
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Styles/bootstrap.css" rel="stylesheet" type="text/css" />

B4: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ Page Title="Dynamically Required Field Validator in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="DynamicallyRequiredFieldValidator._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <h3>
        Dynamically Required Field Validator in ASP.Net
    </h3>
     <asp:CheckBox ID="chkValidator_Code" AutoPostBack="true" Checked="true" Text="Required AccountCode" runat="server" />&nbsp;&nbsp;
     <asp:CheckBox ID="chkValidator_Name" AutoPostBack="true" Checked="true" Text="Required AccountName" runat="server" />&nbsp;&nbsp;
     <asp:CheckBox ID="chkValidator_Region" AutoPostBack="true" Checked="true" Text="Required Region" runat="server" />
     <br />
     <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
         <ContentTemplate>
            <table cellpadding="3" cellspacing="5" border="0" width="75%">
                <tr>
                    <td>
                        <div class="panel panel-default">
                            <div class="panel-heading">
                                <asp:label id="lblHeader" runat="server" Text="EDIT DATA"></asp:label>
                            </div>
                            <div class="panel-body">
                                <table cellspacing="2" cellpadding="3" border="0" width="100%">
                                    <tr>
                                        <td>
                                            <asp:label id="plAccountCode" runat="server" CssClass="CRM_Label"></asp:label>
                                        </td>
                                        <td colspan="3">
                                            <asp:TextBox ID="txtAccCode" CssClass="form-control" runat="server" Width="150px"></asp:TextBox>
                                            <asp:Panel ID="pnlCode" Runat="server" Width="100%" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <asp:Label ID="plAccName" runat="server" CssClass="CRM_Label"></asp:Label>
                                        </td>
                                        <td colspan="3">
                                            <asp:TextBox ID="txtAccName" CssClass="form-control" runat="server" width="516px"></asp:TextBox>
                                            <asp:Panel ID="pnlName" Runat="server" Width="100%" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <asp:Label ID="plAccAddress" runat="server" CssClass="CRM_Label" Text="Address"></asp:Label>
                                        </td>
                                        <td colspan="3">
                                            <asp:TextBox ID="txtAccAddress" CssClass="form-control" TextMode="multiLine" runat="server" Height="45px" width="516px"></asp:TextBox>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="width:48%;">
                                            <asp:Label ID="plPhone" runat="server" CssClass="CRM_Label" Text="Phone"></asp:Label>
                                        </td>
                                        <td style="width:40%;">
                                            <asp:TextBox ID="txtAccPhone" CssClass="form-control" runat="server" width="220px"></asp:TextBox>
                                        </td>
                                        <td style="width:10%;">
                                            <asp:Label ID="plAccFax" runat="server" CssClass="CRM_Label" Text="Fax"></asp:Label>
                                        </td>
                                        <td>
                                            <asp:TextBox ID="txtAccFax" CssClass="form-control" runat="server" width="220px"></asp:TextBox>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <asp:Label ID="plRegion" runat="server" CssClass="CRM_Label"></asp:Label>
                                        </td>
                                        <td colspan="3">
                                            <asp:DropDownList ID="drpRegion" CssClass="form-control" runat="server" width="220px"></asp:DropDownList>
                                            <asp:Panel ID="pnlRegion" Runat="server" Width="100%" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2">
                                            <asp:label id="lblMessage" runat="server"></asp:label><br />
                                        </td>
                                    </tr>
                                </table>
                            </div>
                            <div class="modal-footer">
                                <div class="btn-group">
                                    <asp:LinkButton id="cmdUpdate" runat="server" CssClass="btn btn-small" Causesvalidation="true">
                                        <i class="icon-update"></i>&nbsp;&nbsp;<asp:label id="lblUpdate" runat="server" Text="Update"></asp:label>
                                    </asp:LinkButton>
                                    <asp:LinkButton id="cmdCancel" runat="server" CssClass="btn btn-small" Causesvalidation="false">
                                        <i class="icon-back"></i>&nbsp;&nbsp;<asp:label id="lblBack" runat="server" Text="Back"></asp:label>
                                    </asp:LinkButton>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>       
            </table>
         </ContentTemplate>
     </asp:UpdatePanel>
</asp:Content>

B5: Viết Code cho file Default.aspx
C# Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using System;
using System.Web.UI.WebControls;
using System.Data;

namespace DynamicallyRequiredFieldValidator
{
    public partial class _Default : System.Web.UI.Page
    {
        #region "Dropdownlist"

        private void AddRegion()
        {
            drpRegion.Items.Add(new System.Web.UI.WebControls.ListItem("---Select---", "-1"));
            drpRegion.Items.Add(new System.Web.UI.WebControls.ListItem("Eastern", "1"));
            drpRegion.Items.Add(new System.Web.UI.WebControls.ListItem("Western", "2"));
            drpRegion.Items.Add(new System.Web.UI.WebControls.ListItem("Northern", "3"));
            drpRegion.Items.Add(new System.Web.UI.WebControls.ListItem("Southern", "4"));
        }

        #endregion

        #region "Controls"

        private void CreateRequiredFieldValidator(Panel ucPanel, TextBox ucTextbox, DropDownList ucDropDown, string ErrorMessage)
        {
            RequiredFieldValidator validator = new RequiredFieldValidator();
            ucPanel.Controls.Clear();

            if (ucTextbox != null)
            {
                validator.ID = "val" + ucTextbox.ID;
                validator.ControlToValidate = ucTextbox.ID;
            }
            else if (ucDropDown != null)
            {
                validator.ID = "val" + ucDropDown.ID;
                validator.ControlToValidate = ucDropDown.ID;
                validator.InitialValue = "-1";
            }

            validator.EnableClientScript = true;
            validator.ErrorMessage = ErrorMessage;
            //.Text = "*"
            validator.CssClass = "NormalRed";
            validator.Display = ValidatorDisplay.Dynamic;
            ucPanel.Controls.Add(validator);
        }

        #endregion

        #region "Event Handles"

        protected void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (chkValidator_Code.Checked)
                {
                    plAccountCode.Text = "Account Code (*)";
                    CreateRequiredFieldValidator(pnlCode, txtAccCode, null, "Enter Account Code");
                }
                else
                {
                    plAccountCode.Text = "Account Code";
                }

                if (chkValidator_Name.Checked)
                {
                    plAccName.Text = "Account Name (*)";
                    CreateRequiredFieldValidator(pnlName, txtAccName, null, "Enter Account Name");
                }
                else
                {
                    plAccName.Text = "Account Name";
                }

                if (chkValidator_Region.Checked)
                {
                    plRegion.Text = "Region (*)";
                    CreateRequiredFieldValidator(pnlRegion, null, drpRegion, "Select Region");
                }
                else
                {
                    plRegion.Text = "Region";
                }

                if (!IsPostBack)
                {
                    AddRegion();
                }
            }
            catch
            {
            }
        }

        protected void chkValidator_Code_CheckedChanged(object sender, System.EventArgs e)
              {
                     if (chkValidator_Code.Checked) {
                           plAccountCode.Text = "Account Code (*)";
                           CreateRequiredFieldValidator(pnlCode, txtAccCode, null, "Enter Account Code");
                     } else {
                           plAccountCode.Text = "Account Code";
                     }
              }

        protected void chkValidator_Name_CheckedChanged(object sender, System.EventArgs e)
              {
                     if (chkValidator_Name.Checked) {
                           plAccName.Text = "Account Name (*)";
                           CreateRequiredFieldValidator(pnlName, txtAccName, null, "Enter Account Name");
                     } else {
                           plAccName.Text = "Account Name";
                     }
              }

        protected void chkValidator_Region_CheckedChanged(object sender, System.EventArgs e)
              {
                     if (chkValidator_Region.Checked) {
                           plRegion.Text = "Region (*)";
                           CreateRequiredFieldValidator(pnlRegion, null, drpRegion, "Select Region");
                     } else {
                           plRegion.Text = "Region";
                     }
              }

        protected void cmdUpdate_Click(object sender, System.EventArgs e)
              {
                     try {
                           if (Page.IsValid) {
                                  lblMessage.Text = "Update Sucessfully";
                                  lblMessage.ForeColor = System.Drawing.Color.Green;
                                  lblMessage.Visible = true;
                           }

                     } catch {
                     }
              }

        #endregion
    }
}
VB.NET Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Namespace DynamicallyRequiredFieldValidator

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Dropdownlist"

        Private Sub AddRegion()
            With drpRegion.Items
                .Add(New System.Web.UI.WebControls.ListItem("---Select---", "-1"))
                .Add(New System.Web.UI.WebControls.ListItem("Eastern", 1))
                .Add(New System.Web.UI.WebControls.ListItem("Western", 2))
                .Add(New System.Web.UI.WebControls.ListItem("Northern", 3))
                .Add(New System.Web.UI.WebControls.ListItem("Southern", 4))
            End With
        End Sub

#End Region

#Region "Controls"

        Private Sub CreateRequiredFieldValidator(ByVal ucPanel As Panel, ByVal ucTextbox As TextBox, ByVal ucDropDown As DropDownList, ByVal ErrorMessage As String)
            Dim validator As New RequiredFieldValidator()
     ucPanel.Controls.Clear()
            With validator
                If Not ucTextbox Is Nothing Then
                    .ID = "val" & ucTextbox.ID
                    .ControlToValidate = ucTextbox.ID
                ElseIf Not ucDropDown Is Nothing Then
                    .ID = "val" & ucDropDown.ID
                    .ControlToValidate = ucDropDown.ID
                    .InitialValue = "-1"
                End If

                .EnableClientScript = True
                .ErrorMessage = ErrorMessage
                '.Text = "*"
                .CssClass = "NormalRed"
                .Display = ValidatorDisplay.Dynamic
            End With
            ucPanel.Controls.Add(validator)
        End Sub
      
#End Region

#Region "Event Handles"

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try
                If chkValidator_Code.Checked Then
                    plAccountCode.Text = "Account Code (*)"
                    CreateRequiredFieldValidator(pnlCode, txtAccCode, Nothing, "Enter Account Code")
                Else
                    plAccountCode.Text = "Account Code"
                End If

                If chkValidator_Name.Checked Then
                    plAccName.Text = "Account Name (*)"
                    CreateRequiredFieldValidator(pnlName, txtAccName, Nothing, "Enter Account Name")
                Else
                    plAccName.Text = "Account Name"
                End If

                If chkValidator_Region.Checked Then
                    plRegion.Text = "Region (*)"
                    CreateRequiredFieldValidator(pnlRegion, Nothing, drpRegion, "Select Region")
                Else
                    plRegion.Text = "Region"
                End If

                If Page.IsPostBack = False Then
                    AddRegion()
                End If

            Catch ex As Exception

            End Try
        End Sub

        Private Sub chkValidator_Code_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkValidator_Code.CheckedChanged
            If chkValidator_Code.Checked Then
                plAccountCode.Text = "Account Code (*)"
                CreateRequiredFieldValidator(pnlCode, txtAccCode, Nothing, "Enter Account Code")
            Else
                plAccountCode.Text = "Account Code"
            End If
        End Sub

        Private Sub chkValidator_Name_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkValidator_Name.CheckedChanged
            If chkValidator_Name.Checked Then
                plAccName.Text = "Account Name (*)"
                CreateRequiredFieldValidator(pnlName, txtAccName, Nothing, "Enter Account Name")
            Else
                plAccName.Text = "Account Name"
            End If
        End Sub

        Private Sub chkValidator_Region_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkValidator_Region.CheckedChanged
            If chkValidator_Region.Checked Then
                plRegion.Text = "Region (*)"
                CreateRequiredFieldValidator(pnlRegion, Nothing, drpRegion, "Select Region")
            Else
                plRegion.Text = "Region"
            End If
        End Sub

        Private Sub cmdUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click
            Try
                If Page.IsValid Then
                    lblMessage.Text = "Update Sucessfully"
                    lblMessage.ForeColor = System.Drawing.Color.Green
                    lblMessage.Visible = True
                End If
            Catch ex As Exception

            End Try
        End Sub

#End Region
       
    End Class

End Namespace

Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET




Chúc các bạn thành công!

Quang Bình

Share This:

Post Tags:

Mỗi bài viết đều là công sức và thời gian của tác giả ví vậy tác giả chỉ có một mong muốn duy nhất nếu ai đó có Copy thì xin hãy ghi rõ nguồn và thông tin tác giả ở cuối mỗi bài viết.
Xin cảm ơn!

No Comment to " Tạo RequiredFieldValidator động trong Asp.net "

  • To add an Emoticons Show Icons
  • To add code Use [pre]code here[/pre]
  • To add an Image Use [img]IMAGE-URL-HERE[/img]
  • To add Youtube video just paste a video link like http://www.youtube.com/watch?v=0x_gnfpL3RM