Matt
Matt

Reputation: 5449

Problem finding a control within a FormView from code-behind

Here the code behind... I'm trying to retrieve this control so I can add items to the drop down list (I'm retrieving the Role Groups to add to the drop down list in the code-behind)

Protected Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim DDRoleGroups As DropDownList
    DDRoleGroups = FormView1.FindControl("DDRoleGroup")
End Sub

Here's the FormView: (I took out most of the fields so it's easier to read)

<asp:FormView ID="FormView1" runat="server" DataKeyNames="ID" 
     DataSourceID="ObjectDataSource_Vendors" 
     DefaultMode="Insert" BorderColor="DarkGray" 
     BorderStyle="Solid" BorderWidth="1px" CellPadding="4" Visible="False"> 
  <EditItemTemplate> 
  </EditItemTemplate> 
  <InsertItemTemplate>                          
    <label class="form_label">Role Group:</label><br /><asp:DropDownList ID="DDRoleGroup" 
               runat="server" Width="175px"
               EnableViewState="False"> 
              </asp:DropDownList>
   </InsertItemTemplate>
</asp:FormView>

Could it possibly have to do with the fact that it's in the Page_Load sub and the control hasn't acctually loaded yet?

Thanks,
Matt

Upvotes: 4

Views: 18227

Answers (2)

devio
devio

Reputation: 37215

Your dropdown only exists in Insert mode. Try to implement the formview's ModeChanged event and retrieve the control if CurrentMode == Insert:

protected void FormView1_ModeChanged(object sender, EventArgs e)
{
    if (FormView1.CurrentMode == FormViewMode.Insert)
    {
        DropDownList DDRoleGroups = FormView1.FindControl("DDRoleGroup");
        // fill dropdown
    }
}

You cannot handle this in Page_Load, as the form has not yet switched into Insert mode.

Upvotes: 3

womp
womp

Reputation: 116977

FindControl on a formview will only work for the template that the FormView's "CurrentMode" property is set to.

In your case, you can only do FindControl for "DDRoleGroups" if your FormView is set to "Insert", since that's the template that your control exists in.

Hope that helps.

Upvotes: 1

Related Questions