(ASP.NET compare end time and start time with customvalidator) – Khi cần so sánh dữ liệu Currency, Double, Date, Integer, String giữa 2 Control Textbox hoặc Dropdownlist người lập trình có thể sử dụng Control CompareValidator.  Với CompareValidator người lập trình có thể dễ dàng so sánh >=, <=, = giữa các Control với nhau. Tuy nhiên khi chúng ta cần so sánh giá trị kiểu thời gian (Time) từ 2 Dropdownlist có sẵn? Ví dụ bây giờ chúng ta không cho phép thời gian bắt đầu lớn hơn thời gian kết thúc như hình phía dưới.  Dưới đây là cách giải quyết vấn đề so sánh giá trị kiểu thời gian với 2 Dropdownlist.

Nghe những bài hát đỉnh nhất về Thấy cô giáo - 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: Mở file Default.aspx dưới dạng HTML và  nhập mã HTML
<%@ PageTitle="Compare Validation for Dropdownlist with Time in Asp.net" Language="vb"MasterPageFile="~/Site.Master"AutoEventWireup="false"CodeBehind="Default.aspx.vb"Inherits="CustomValidatorCompareTimeValues._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>
    <h4>
        Compare Validation for Dropdownlist with Time in Asp.net
    </h4>
     <asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
         <ContentTemplate>
            <table cellpadding="3"cellspacing="5"border="0"width="60%">
                <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 style="width:14%;">
                                            <asp:label id="plDate" runat="server"CssClass="CRM_Label"Text="Date"></asp:label>
                                        </td>
                                        <td>
                                           <asp:TextBox ID="txtDate"CssClass="form-control"runat="server"Width="85px"></asp:TextBox>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td valign="top">
                                            <asp:label id="plTime" runat="server"CssClass="CRM_Label"Text="Time"></asp:label>
                                        </td>
                                        <td>
                                             <table cellpadding="0"cellspacing="0"width="100%">
                                                <tr>
                                                    <tdstyle="width:20%;">
                                                        <asp:label id="plTime_Start"CssClass="Normal"runat="server"Text="Start "></asp:label>
                                                        <asp:DropDownList ID="ddlTimeFrom"CssClass="form-control"Runat="server"  Width="120px"></asp:DropDownList>
                                                        <asp:label id="plTime_End"CssClass="Normal"runat="server"Text=" End "></asp:label>
                                                        <asp:DropDownList ID="ddlTimeTo"CssClass="form-control"Runat="server"  Width="120px"></asp:DropDownList>
                                                        <asp:CustomValidator ID="ddlValidator"CssClass="NormalRed"runat="server"ErrorMessage="End time should be greater than Start" onservervalidate="ddlValidator_ServerValidate" />
                                                    </td>
                                                </tr>
                                            </table>
                                        </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>

B3: 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 CustomValidatorCompareTimeValues
{
    public partial class _Default : System.Web.UI.Page
    {
        #region"ComboData"

        private voidLoadComboData()
        {
            //Set start time (00:00 means 12:00 AM)
            DateTime StartTime = DateTime.ParseExact("07:00", "HH:mm", null);
            //Set end time (23:55 means 11:55 PM)
            DateTime EndTime = DateTime.ParseExact("22:00", "HH:mm", null);
            //Set 15 minutes interval
            TimeSpan Interval = newTimeSpan(0, 15, 0);
            ddlTimeFrom.Items.Clear();
            ddlTimeTo.Items.Clear();
            while (StartTime <= EndTime)
            {
                ddlTimeFrom.Items.Add(StartTime.ToShortTimeString());
                ddlTimeTo.Items.Add(StartTime.ToShortTimeString());
                StartTime = StartTime.Add(Interval);
            }
            ddlTimeTo.SelectedIndex = 10;
        }

        #endregion

        #region"Event Handles"

        protected voidPage_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    LoadComboData();
                }
            }
            catch
            {
            }
        }

        private voidcmdUpdate_Click(object sender, System.EventArgs e)
        {
            try
            {
                if (Page.IsValid)
                {

                }
            }
            catch
            {
            }
        }

        protected voidddlValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            DateTime dFrom = DateTime.Parse(ddlTimeFrom.SelectedValue);
            DateTime dTo = DateTime.Parse(ddlTimeTo.SelectedValue);
            TimeSpan TS = dTo - dFrom;

            if (TS.TotalHours <= 0)
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }
        #endregion
    }
}
VB.NET Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Namespace CustomValidatorCompareTimeValues

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "ComboData"

        Private SubLoadComboData()
            'Set start time (00:00 means 12:00 AM)
            Dim StartTime As DateTime = DateTime.ParseExact("07:00", "HH:mm", Nothing)
            'Set end time (23:55 means 11:55 PM)
            Dim EndTime As DateTime = DateTime.ParseExact("22:00", "HH:mm", Nothing)
            'Set 15 minutes interval
            Dim Interval As New TimeSpan(0, 15, 0)
            ddlTimeFrom.Items.Clear()
            ddlTimeTo.Items.Clear()
            While StartTime <= EndTime
                ddlTimeFrom.Items.Add(StartTime.ToShortTimeString())
                ddlTimeTo.Items.Add(StartTime.ToShortTimeString())
                StartTime = StartTime.Add(Interval)
            End While
            ddlTimeTo.SelectedIndex = 10
        End Sub

#End Region

#Region "Event Handles"

        Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
            Try
                If NotIsPostBack Then
                    LoadComboData()
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private SubcmdUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdUpdate.Click
            Try
                If Page.IsValid Then
                  
                End If
            Catch ex As Exception

            End Try
        End Sub

        Protected SubddlValidator_ServerValidate(ByVal source As Object, ByVal args As ServerValidateEventArgs)
            Dim dFrom As DateTime = ddlTimeFrom.SelectedValue
            Dim dTo As DateTime = ddlTimeTo.SelectedValue
            Dim TS As TimeSpan = dTo - dFrom

            If TS.TotalHours <= 0 Then
                args.IsValid = False
            Else
                args.IsValid = True
            End If
        End Sub

#End Region

    End Class

End Namespace

Bây giờ khi chạy Project, mỗi khi người sử dụng lựa chọn thời gian kết thúc lớn hơn thời gian bắt đầu thì sẽ được phép Save. Nhưng khi chọn thời gian bắt đầu lớn hơn thời gian kết thúc thì khi kích nút Save một thông báo sẽ xuất hiện yêu cầu người sử dụng phải chọn lại thời gian.


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

0 comments Blogger 0 Facebook

Post a Comment

 
lập trình đốt nét © 2013. All Rights Reserved. Powered by Blogger
Top