简体   繁体   中英

How do I bind a DropDownList after postback?

I have an aspx site with a DropDownList in it. I want to be able to choose between 3 variables there and then keep the chosen value for the postback. The page is made so that it loads 10 entries from the database and with this DropDownList I want to be able to choose between 10, 20, 30 entries.

DropDownList

<asp:DropDownList ID="dd1" runat="server" AutoPostBack="True"  EnableViewState="True">
    <asp:ListItem Value="10">10</asp:ListItem>
    <asp:ListItem Value="20">20</asp:ListItem>
    <asp:ListItem Value="30">30</asp:ListItem>
</asp:DropDownList>

Here I am trying to set the value that is being sent to the database for the query that brings out the 10, 20 or 30 first entries.

public IEnumerable<XX> repOrder_GetData([ViewState]DateTime? UpdatedRows)
{
    var ordrar = _facade.OrderGetForAttest(1, Convert.ToInt32(dd1.SelectedValue));

    return ordrar;
}

How do I retain this value during a postback because the page will reload every time you choose something in the DropDownList resulting in only the first value ever being chosen.

protected void Page_Init(object sender, EventArgs e)
        {
            try
            {
                _masterpage = this.Master as XX.resource.masterpage.Site;

            }
            catch (Exception)
            {
                throw;
            }
        }


       protected void Page_Load(object sender, EventArgs e)
    {
        // Kolla behörighet första gången.
        KollaBehorighet();

        _masterpage.ClearMessage();

        if (Page.IsPostBack)
        {

        }
        else
        {
            Page.DataBind();
            // Första gången..
            PageInit();
            FillPage(null);
            //FIXME: xxx.Focus();                             
        }

    }

You should set the 'OnSelectedIndexChanged' event.

<asp:DropDownList ID="dd1" runat="server" AutoPostBack="True" onselectedindexchanged="ddlItemSelected"  EnableViewState="True">
    <asp:ListItem Value="10">10</asp:ListItem>
    <asp:ListItem Value="20">20</asp:ListItem>
    <asp:ListItem Value="30">30</asp:ListItem>
</asp:DropDownList>


protected void ddlItemSelected(object sender, EventArgs e)
{
//Add your selected value to viewstate or session or whatever. Then check this value when binding on postback.
Viewstate["myValue"] = dd1.SelectedValue;
}

You can try to store it in Session state and then load it from session Some like this:

Session["Selected"] = dd1.SelectedIndex;

And in Load Event you can use:

dd1.SelectedIndex = Convert.ToInt32(Session["Selected"]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM