Setting SelectedIndex problems

F

Filip

Hi all,

I am having a problem with the DropDownList control
consider the following code :
<script language="VB" runat="server">
Sub Page_Load(S As Object, E As EventArgs)
ddl.Items.Add("")
ddl.Items.Add("item1")
ddl.Items.Add("item2")
ddl.Items.Add("item3")
ddl.SelectedIndex = ddl.Items.IndexOf
(ddl.Items.FindByText("item3"))
SelIndex.Text = ddl.SelectedIndex
SelText.Text = ddl.SelectedItem.Text
End Sub
</script>
<html><head></head><body>
<form runat="server">
<asp:DropDownList ID="ddl" Runat="server"/>
<asp:Label ID="SelIndex" Runat="server"/>
<asp:Label ID="SelText" Runat="server"/>
</form></body></html>

In the Labels SelIndex and SelText, the correct values are
displayed (index = 3, text = item3)
But the visual text in the DropDownList control itself does
not change (it displays "item1")

I am probably missing something elementary here (I am new
to ASP.Net, so sorry if I am asking stupid or evident things)
Can someone help me with this? Thanks.

Filip.
 
S

S. Justin Gengo

Filip,

This is a common mistake.

Every time you post back your page load routine is run. And it is resetting
your drop down list.

Wrap the code that is putting items into your drop down list in an if then
like this:

If Not Page.IsPostBack Then
'---Add dropdownlist/bind dropdownlist here
ddl.Items.Add("")
ddl.Items.Add("item1")
ddl.Items.Add("item2")
ddl.Items.Add("item3")
ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByText("item3"))
End If

--
Sincerely,

S. Justin Gengo, MCP
Web Developer / Programmer

www.aboutfortunate.com

"Out of chaos comes order."
Nietzsche
 
S

S. Justin Gengo

Oh, by the way, you can choose an item in the list much more easily...

ddl.SelectedValue = "item3"

--
Sincerely,

S. Justin Gengo, MCP
Web Developer / Programmer

www.aboutfortunate.com

"Out of chaos comes order."
Nietzsche
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top