macemers
macemers

Reputation: 2222

Why can't get the right value of dropdownlist in 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);

        }

Upvotes: 4

Views: 3674

Answers (2)

Thomas
Thomas

Reputation: 1563

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...

Upvotes: 9

bkwint
bkwint

Reputation: 626

First of did you debug this??? Cause the C# code seems corrent.

Try changing this:

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

To

<asp:button id="btnSmt" runat="server" Text="Submit" OnClick="btnSmt_Click" /> 

if this truely is your code your click event would never have been caught, therefor if you would put a breakpoint in your C# code you would have seen that the action is not triggered.

Anyway, hope it helps

Upvotes: 0

Related Questions