views:

2141

answers:

2

Okay, I have a FormView with a couple of child controls in an InsertItemTemplate. One of them is a DropDownList, called DdlAssigned. I reference it in the Page's OnLoad method like so:

protected void Page_Load(object sender, EventArgs e)
{
    ((DropDownList)FrmAdd.FindControl("DdlAssigned")).SelectedValue =
          ((Guid)Membership.GetUser().ProviderUserKey).ToString();
}

Basically I'm just setting the default value of the DropDownList to the user currently logged in.

Anyway, when the page finishes loading the SelectedValue change isn't reflected on the page. I stepped through OnLoad and I can see the change reflected in my Watch list, but when all is said and done nothing's different on the page.

+3  A: 

I figured it out. I'm still missing exactly why it doesn't work just on FormLoad, but performing the change in the FormView's DataBound event does the trick.

protected void FrmAdd_DataBound(object sender, EventArgs e)
{
    // This is the same code as before, but done in the FormView's DataBound event.
    ((DropDownList)FrmAdd.Row.FindControl("DdlAssigned")).SelectedValue =
     ((Guid)Membership.GetUser().ProviderUserKey).ToString();
}

So, I guess the general rule of thumb is that if you are having problems making changes to controls when working with databinding, try to make them immediately after it has been bound.

Dusda
Wow, old topic. I can confirm that DataBound DropDownLists are not populated with their values when OnLoad runs, so setting the SelectedValue doesn't do any good.
Dave
A: 

I had a problem with dropdownlists and making the first value say something like, "Please select a value..." but without making it an actual selectable item, nor show up on the dropdownlist. I was binding the ddl in the page_load and I have to make sure that I set the text of the dropdownlist, AFTER it's been bound with data. You've accomplished the same thing by adding it to your databound section.

GregD