Capture a value from a dropdownlist where the display dropdownlist is not default

  • A+
Category:Languages

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;     } } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: