In this
article I will explain How to fill dropdownlist at runtime with time interval of specified minutes or hours e.g. 5
minutes, 15
minutes, 1 hour, 5 hours etc as per requirement.
Source Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset style="width:250px">
<legend>Select Time
</legend>
From: <asp:DropDownList ID="ddlTimeFrom" runat="server"></asp:DropDownList>
To: <asp:DropDownList ID="ddlTimeTo" runat="server"></asp:DropDownList>
</fieldset>
</div>
</form>
</body>
</html>
Asp.Net C# Code to bind time in DropDownList at runtime with 5 minutes interval
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindTime();
}
}
private void BindTime()
{
// Set the
start time (00:00 means 12:00 AM)
DateTime StartTime = DateTime.ParseExact("00:00","HH:mm",null);
// Set the end
time (23:55 means 11:55 PM)
DateTime EndTime = DateTime.ParseExact("23:55", "HH:mm", null);
//Set 5 minutes interval
TimeSpan Interval = new TimeSpan(0,5,0);
//To set 1
hour interval
//TimeSpan
Interval = new TimeSpan(1, 0,
0);
ddlTimeFrom.Items.Clear();
ddlTimeTo.Items.Clear();
while (StartTime
<= EndTime)
{
ddlTimeFrom.Items.Add(StartTime.ToShortTimeString());
ddlTimeTo.Items.Add(StartTime.ToShortTimeString());
StartTime =
StartTime.Add(Interval);
}
ddlTimeFrom.Items.Insert(0, new ListItem("--Select--", "0"));
ddlTimeTo.Items.Insert(0, new ListItem("--Select--", "0"));
}
Asp.Net VB Code to bind time in DropDownList at runtime with 5 minutes interval
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
BindTime()
End If
End Sub
Private Sub BindTime()
'Set start
time (00:00 means 12:00 AM)
Dim StartTime As DateTime = DateTime.ParseExact("00:00", "HH:mm", Nothing)
'Set end time
(23:55 means 11:55 PM)
Dim EndTime As DateTime = DateTime.ParseExact("23:55", "HH:mm", Nothing)
'Set 5 minutes interval
Dim Interval As New TimeSpan(0, 5, 0)
'To set 1 hour interval
'Dim Interval
As New TimeSpan(1, 0, 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
ddlTimeFrom.Items.Insert(0, New ListItem("--Select--", "0"))
ddlTimeTo.Items.Insert(0, New ListItem("--Select--", "0"))
End Sub
0 comments:
Post a Comment