2013-04-03 1 views
0

J'ai un Multiformview dans ma page aspx comme:FindControl d'un FormView qui est à l'intérieur d'un contrôle utilisateur

<data:MultiFormView ID="mFormView1" DataKeyNames="Id" runat="server" DataSourceID="DataSource"> 

      <EditItemTemplate> 
       <ucl:myControl ID="myControl1" runat="server" /> 
      </EditItemTemplate> 

Et à l'intérieur de mon contrôle utilisateur 'MyControl' Je adropdownlist comme ci-dessous:

<asp:FormView ID="FormView1" runat="server" OnItemCreated="FormView1_ItemCreated"> 
    <ItemTemplate> 
     <table border="0" cellpadding="3" cellspacing="1"> 

      <tr> 
       <td> 
        <asp:DropDownList ID="ddlType" runat="server" Width="154px" /> 
       </td> 
      </tr> 

Alors, quand je l'ai essayé d'accéder à ce d ropdownlist dans mon fichier ascx.cs il me donne une erreur de référence nulle.

J'ai essayé suivante:

protected void FormView1_ItemCreated(Object sender, EventArgs e) 
    { 
      DropDownList ddlType= FormView1.FindControl("ddlType") as DropDownList; 
    } 

ET

DropDownList ddlType= (DropDownList)FormView1.FindControl("ddlType"); 

ET: A l'intérieur Databound aussi. Rien ne fonctionne.

EDIT:

Je ne vérifiait pas que Formview1.Row est nulle ou non. Voici la solution:

protected void FormView1_DataBound(object sender, EventArgs e) 
    { 
     DropDownList ddlType = null; 
     if (FormView1.Row != null) 
     { 
      ddlType = (DropDownList)FormView1.Row.FindControl("ddlType"); 
     } 
    } 

Répondre

1

Je ne vérifiais pas que Formview1.Row est null ou non. Voici la solution:

protected void FormView1_DataBound(object sender, EventArgs e) 
    { 
     DropDownList ddlType = null; 
     if (FormView1.Row != null) 
     { 
      ddlType = (DropDownList)FormView1.Row.FindControl("ddlType"); 
     } 
    } 
2

Voici une méthode d'extension, qui permet de rechercher récursive. Il étend vos constrols actuels avec la méthode FindControlRecursive.

using System; 
using System.Web; 
using System.Web.UI; 

public static class PageExtensionMethods 
{ 
    public static Control FindControlRecursive(this Control ctrl, string controlID) 
    { 
     if (ctrl == null || ctrl.Controls == null) 
      return null; 

     if (String.Equals(ctrl.ID, controlID, StringComparison.OrdinalIgnoreCase)) 
     { 
      // We found the control! 
      return ctrl; 
     } 

     // Recurse through ctrl's Controls collections 
     foreach (Control child in ctrl.Controls) 
     { 
      Control lookFor = FindControlRecursive(child, controlID); 
      if (lookFor != null) 
       return lookFor; 
      // We found the control 
     } 
     // If we reach here, control was not found 
     return null; 
    } 
} 
Questions connexes