Problem finding a control within a FormView from code-behind

Matt picture Matt · Jun 24, 2009 · Viewed 17.8k times · Source

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

Answer

devio picture devio · Jul 18, 2009

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.