Hi nauna,
Check this example. Now please take its reference and correct your code.
Database
CREATE TABLE tblTimes
(
Id INT IDENTITY PRIMARY KEY,
Time VARCHAR(10)
)
INSERT INTO tblTimes VALUES
('12:00 PM'),('02:00 PM'),('05:00 PM'),
('07:00 PM'),('08:00 AM'),('10:00 AM')
SELECT * FROM tblTimes
HTML
<asp:TextBox ID="TextBox1" runat="server" TextMode="Date"
OnTextChanged="DateChanged" AutoPostBack="true"></asp:TextBox>
<asp:DropDownList runat="server" ID="ddlTimes">
</asp:DropDownList>
Code
C#
protected void DateChanged(object sender, EventArgs e)
{
DateTime selectedDate = Convert.ToDateTime(TextBox1.Text.Trim());
List<ListItem> times = GetTime();
for (int i = times.Count; i > 0; --i)
{
DateTime dt;
if (!DateTime.TryParse(times[i - 1].Text, out dt)) { }
if (dt <= DateTime.Now && selectedDate == DateTime.Today)
{
times.RemoveAt(i - 1);
}
}
ddlTimes.DataSource = times;
ddlTimes.DataTextField = "Text";
ddlTimes.DataValueField = "Value";
ddlTimes.DataBind();
}
private List<ListItem> GetTime()
{
List<ListItem> times = new List<ListItem>();
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = "SELECT * FROM tblTimes";
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
times.Add(new ListItem()
{
Text = Convert.ToDateTime(sdr["Time"]).ToString("hh:mm tt"),
Value = Convert.ToDateTime(sdr["Time"]).ToString("hh:mm tt")
});
}
con.Close();
}
return times;
}
VB.Net
Protected Sub DateChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim selectedDate As DateTime = Convert.ToDateTime(TextBox1.Text.Trim())
Dim times As List(Of ListItem) = GetTime()
For i As Integer = times.Count To 1 Step -1
Dim dt As DateTime
If Not DateTime.TryParse(times(i - 1).Text, dt) Then
End If
If dt <= DateTime.Now AndAlso selectedDate = DateTime.Today Then
times.RemoveAt(i - 1)
End If
Next
ddlTimes.DataSource = times
ddlTimes.DataTextField = "Text"
ddlTimes.DataValueField = "Value"
ddlTimes.DataBind()
End Sub
Private Function GetTime() As List(Of ListItem)
Dim times As List(Of ListItem) = New List(Of ListItem)()
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim query As String = "SELECT * FROM tblTimes"
Using con As SqlConnection = New SqlConnection(conString)
Dim cmd As SqlCommand = New SqlCommand(query, con)
con.Open()
Dim sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
times.Add(New ListItem() With {
.Text = Convert.ToDateTime(sdr("Time")).ToString("hh:mm tt"),
.Value = Convert.ToDateTime(sdr("Time")).ToString("hh:mm tt")
})
End While
con.Close()
End Using
Return times
End Function
Screenshot