Viewstate erased on databind?

T

tal_mcmahon

Hello all,

I have a user control (ascx) that has a DropDownList on it.
The User Control exposes the selectedvalue/text of the ddl.
The User Control Has a Click event.

I place that User control on the page dynamically in the OnInit.
In the Click event for the control I am trying to acces the properties
like this:
string s
s= ((NewUserSection)ph.FindControl("uc")).SelectedUserTypeText

If i populate the drop down in the page load of the control like this
(my belief of what is the standard way):

this.ddl.DataSource=sqlReader;
this.ddl.DataTextField="ENTITY_NAME";
this.ddl.DataValueField="ROLE_ID";
this.ddl.DataBind();

I only ever get the first item in the list.
I assume I am losing view state.

If I populate the drop down in the page load of the control like this:

while (reader.Read())
{
ddl.Items.Add(new ListItem(reader["ENTITY_NAME"].ToString(),
reader["ROLE_ID"].ToString());
}

When the onclick is fired I get the selected text as requested.

WHY???

what is happening in the databind that is not when I do it by hand?

I have run the code both ways side by side and one works and one does
not.

just curious at this point.

Tal
 
D

Dale Preston

You should be testing IsPostBack before doing your databind:

if (!IsPostBack)
{
this.ddl.DataSource=sqlReader;
this.ddl.DataTextField="ENTITY_NAME";
this.ddl.DataValueField="ROLE_ID";
this.ddl.DataBind();
}

Also, in your second example, unless you're doing something that you're not
showing, you're just adding the contents of your sqlReader to the end of the
dropdownlist, leaving the original contents there as well. So your code can
retrieve the selection but the contents will all be there twice or more, as
you load and reload the page.

HTH

Dale Preston
MCAD, MCDBA, MCSE
 

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

Top