Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 378
Ariff Naj Avatar asked Oct 31 '18 04:10

Ariff Naj


2 Answers

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;
    }
}
like image 97
Tetsuya Yamamoto Avatar answered Nov 14 '22 21:11

Tetsuya Yamamoto


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;
    }
}
like image 28
Siavash Avatar answered Nov 14 '22 22:11

Siavash