Setting SelectedIndex problems

  • Thread starter Thread starter Filip
  • Start date Start date
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.
 
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
 
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
 
Back
Top