Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't get the right value of dropdownlist in asp.net

Tags:

html

c#

asp.net

I have following codes in asp.net:

<asp:dropdownlist id="ddlApp" runat="server" />
<asp:button id="btnSmt" runat="server" Text="Submit" />

and code behind:

    private void btnSmt_Click(object sender, System.EventArgs e)
    {
            lbl.Text = ddlApp.SelectedItem.Value;           
    }

The logic is very simple. Get the selected value of dropdownlist and pass it to lbl.text.

But the problem is no matter how I try, the text show the fist value of list in the dropdownlist rather than the selected value.

And I notice that everytime I click the button the page refresh.

Please help.

BTW, I have the following event binding:

private void InitializeComponent()
        {    
            this.btnSmt.Click += new System.EventHandler(this.btnSmt_Click);
            this.Load += new System.EventHandler(this.Page_Load);
            this.ddlApp.SelectedIndexChanged +=new System.EventHandler(this.ddlApp_Change);

        }
like image 271
macemers Avatar asked Feb 18 '23 21:02

macemers


1 Answers

You have to do the binding for the dropdownlist in

if (!Page.IsPostBack)

Else it will re-build the items for the dropdown list on every postback and therefore only return the currently selected item in the new collection - which is the first.

It also looks like you're missing the btnSmt_Click on the button - but you've probably set it somewhere else...

like image 138
Thomas Avatar answered Feb 27 '23 12:02

Thomas