capture value from dropdownlist where the display dropdownlist is not default

  • A+
Category:Languages

I want to capture selected date on my DropDown list, where there 5 day will display on DropdownList. I'm usually put default value on DropDown, but not this time because in drop down list i want it always display current date and next 5 day. 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 SelectedValue property value may be different from 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: