Need help with code.

  • Thread starter Thread starter Aaron
  • Start date Start date
A

Aaron

I have a session variable populated with a name.
I also have a dropdownlist populated with several names.
I would like to select the name in the dropdown that matches the name in the
session variable.

I am trying :
'DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(Session("Name"))

This does not work.

Any ideas?

Thanks,
Aaron
 
hmmm

does the right hand side return -1?

If so it isn't finding a match.

without knowing the value of everything it would be hard to see the problem
I think.

could you set a break point and check on all the values...
 
DropDownList1.Items.FindByValue(Session("Name").ToString).Selected = True

HTH,
Greg
 
Guess this works as the other is looking for an object instance I think.
 
Not sure what you are trying to accomplish, but I always found this bit of
code pretty slick. If your dropdown list is in a datagrid, and you are
trying to preset an item from db when put into edit mode, you may find this
slick too. Basically it stores the original value from the db in a custom
attribute named... OriginalValue.

Hope it make sense and is relevant.
Greg


<asp:dropdownlist id=DropDownList1 Runat="server" OriginalValue='<%#
DataBinder.Eval(Container.DataItem, "SomeFieldName") %>'>
<asp:ListItem Value="">--choose--</asp:ListItem>
<asp:ListItem Value="0">Choice 1</asp:ListItem>
<asp:ListItem Value="1">Choice 2</asp:ListItem>
</asp:dropdownlist>


Protected Sub grid_ItemDataBound(ByVal obj As System.Object, ByVal e As
System.Web.UI.WebControls.DataGridItemEventArgs) Handles grid.ItemDataBound

If e.Item.ItemType = ListItemType.EditItem Then

Dim Myddl As DropDownList =
CType(e.Item.FindControl("DropDownList1"), DropDownList)
Dim OriginalValue As String = Myddl.Attributes("OriginalValue")
Dim MyListItem As ListItem =
Myddl.Items.FindByValue(OriginalValue)
ddlType.SelectedIndex = ddlType.Items.IndexOf(MyListItem)

End If

End Sub
 
typo is last post...

ddlType.SelectedIndex = ddlType.Items.IndexOf(MyListItem)

should have been

Myddl.SelectedIndex = Myddl.Items.IndexOf(MyListItem)

(forgot I renamed ddlType to Myddl for example)

This also points out the error in your original post...
DropDownList1.SelectedIndex =DropDownList1.Items.IndexOf(Session("Name"))

needs to be changed to

DropDownList1.SelectedIndex
=DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(Session("Name")
..ToString)

but my first post should work too

DropDownList1.Items.FindByValue(Session("Name").ToString).Selected = True

Confused yet? I am. :^)
Greg
 

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

Back
Top