dropdownlist.selectedItem not working from in a datalist

S

sling blade

Hi,

I have a dropdownlist in my DataList control and I am trying to set the
SelectedItem property of the dropdownlist so when the datalist displays
the user will see the text in the dropdownlist set to a predetermined
value.

I can set the SelectedItem property easy enough and get the
dropdownlist to work fine just so long as the dropdownlist is just on
the form itself not in a DataList control.

For some reason when its in a DataList control the dropdownlist will
show the first item in the list and not the one selected.

I am setting the selectedItem property from the datalist's ItemCreated
command.
Here is the code from the item created event:

If e.Item.ItemType = ListItemType.Item Or _
e.Item.ItemType = ListItemType.AlternatingItem Then

Dim ddlCategory As DropDownList

Try

ddlCategory = CType(e.Item.FindControl("ddlCategory"),
DropDownList)

Dim myDataSet As New DataSet
Dim strSQL As String = "SELECT CategoryID, CategoryName
FROM Category"
Dim myAdapter As New OleDbDataAdapter(strSQL,
c.Connection)

myAdapter.Fill(myDataSet)
ddlCategory.DataSource = myDataSet
ddlCategory.DataTextField = "CategoryName"
ddlCategory.DataValueField = "CategoryID"
ddlCategory.SelectedValue = myvalue
ddlCategory.DataBind()
Catch ex As Exception
Response.Write(ex.Message.ToString)
End Try
End If

Right after this code has ran I have checked the SelectedValue text and
it is set to myvalue eg.
dim strTest as string = ddlCategory.SelectedValue.ToString

strTest does equal myvalue, however when the grid displays it is always
set to the first value generated from the dataset and not the
selectedvalue.

Any ideas on how to set the SelectedValue from in a DataList?

Thanks
 
B

Burak SARICA

Check page load event.
If Page.IsPostBack property is true, then you shouldn't re-bind and
initialize your database stuff.

Burak SARICA
 
S

sling blade

I have a "If Not IsPostBack is True Then BindGrid" routine in my Page
Load event for the DataList.

Once the DataList binds then the ItemCreated event fires and I create a
oledbcommand object and use it to bind stuff to the dropdownlist.

Does this sound like the right procedure?
 
B

Burak SARICA

Not just wrong. But if your dropdownlists doesn't change row by row, it
creates useless traffic and cpu time. So fill a global dataTable for the
dropdowns, and only bind them in itemcreate event.
 

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,968
Messages
2,570,154
Members
46,702
Latest member
LukasConde

Latest Threads

Top