DropDownList not giving the selected item when a Button is clicked... please help newbie...

J

Julius Mong

Hi dear experts,

I'm new to ASP.NET and am having a hard time trying to make this work :( I
have a ddl which contains 2 or more items (populated by code) and a submit
asp:button that I'd want when clicked simply sends the ddl's selected item's
text value to an asp:label. I have searched through google for a couple of
days and have tried many things like setting autopostback on the ddl but
nothing is working :( I simply can't work my head round this...

I now have :

<form id="Form1" method="post" runat="server">
<P>
<table cellSpacing="10" cellPadding="0" width="880" border="0">
<tr>
<td id="content_0">
<P><asp:dropdownlist id="lstServer" runat="server"
Width="168px"></asp:dropdownlist>&nbsp</P>
<P><asp:button id="btnSubmit" runat="server"
Text="Submit"></asp:button>&nbsp;
<P><asp:label id="lblStatus" runat="server">Server Status
:</asp:label>&nbsp;</P>
</td>
</tr>
</table>
</P>
</form>

and in the aspx.cs I have the method registered to the click event:

private void btnSubmit_Click(object sender, System.EventArgs e)
{
lblStatus.Text = lstServer.SelectedItem.Text ;
}

However it is always showing the first item in the ddl... I have tried
putting a public string in teh webform class and on the ddl's
selectedindexchange store that selectedvalue to the public string and
retrieve it when Page.IsPostBack on Page_Load and have btnSubmit_Click get
the string instead, but it is always the first item int he ddl still... I am
so confused... could someone kindly point me int he right direction
please... or let me know where on the Web I should look...

Thanks tonnes!!!

Jules
 
A

Asela Gunawardena

this is simply because the dropdownlist is being re-initializing [being
bound over and over] with the page load (since you have set autopost back to
true) what you have to do is check for postback and do the binding only whn
the page is not posted back

e.g
if(!IsPostBack)
{
// do you binding here so that the dropdownlist would not be bound
each time the page is posted to the server
}

this should work.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top