I want to capture the selected date on my DropDown
list, where there are five days will display on DropdownList
.
I'm usually putting the default value on DropDown
, but not this time because in the drop down list I want it always display the current date and the next five days. But I don't know how to capture the data.
<asp:DropDownList ID="ddldate" runat="server">
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
List<ListItem> items = new List<ListItem>();
for (int i = 0; i < 5; i++)
{
items.Add(new ListItem(
DateTime.Now.AddDays(i).ToShortDateString(),
DateTime.Now.AddDays(i).ToShortDateString()));
}
ddldate.DataSource = items;
ddldate.DataBind();
ddldate.Items[0].Selected = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
string deliverytime = ddldate.SelectedValue.ToString();
lbltest.Text = deliverytime;
}
You're repopulating the DropDownList
for every postback and reloading the page, hence the SelectedValue
property value may be different from the posted value. Just put a check against IsPostBack
to prevent repopulating DropDownList
data on postback:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<ListItem> items = new List<ListItem>();
for (int i = 0; i < 5; i++)
{
items.Add(new ListItem(DateTime.Now.AddDays(i).ToShortDateString(), DateTime.Now.AddDays(i).ToShortDateString()));
}
ddldate.DataSource = items;
ddldate.DataBind();
ddldate.Items[0].Selected = true;
}
}
You should not bind data on PostBack
, change your FormLoad
code to below sample:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
List<ListItem> items = new List<ListItem>();
for (int i = 0; i < 5; i++)
{
items.Add(new ListItem(DateTime.Now.AddDays(i).ToShortDateString(), DateTime.Now.AddDays(i).ToShortDateString()));
}
ddldate.DataSource = items;
ddldate.DataBind();
ddldate.Items[0].Selected = true;
}
}
If you check the PostBack
property as condition, your SelectedValue
will keep, otherwise DropDown
will bind on each page-post.
And I also recommend you to check SelectedValue
status before use it, don't try to get value if this null
, check the following code:
protected void Button1_Click(object sender, EventArgs e)
{
if(ddldate.SelectedValue != null)
{
string deliverytime = ddldate.SelectedValue.ToString();
lbltest.Text = deliverytime;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With