Reputation: 1081
I have a Multiformview inside my aspx page like:
<data:MultiFormView ID="mFormView1" DataKeyNames="Id" runat="server" DataSourceID="DataSource">
<EditItemTemplate>
<ucl:myControl ID="myControl1" runat="server" />
</EditItemTemplate>
And inside my user control 'mycontrol' I have adropdownlist like below:
<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>
So when i tried to access this dropdownlist inside my ascx.cs file it is giving me null reference error.
I tried following:
protected void FormView1_ItemCreated(Object sender, EventArgs e)
{
DropDownList ddlType= FormView1.FindControl("ddlType") as DropDownList;
}
AND
DropDownList ddlType= (DropDownList)FormView1.FindControl("ddlType");
AND: Inside Databound also. Nothing is working.
EDIT:
I Was not checking that Formview1.Row is null or not. Here is the solution:
protected void FormView1_DataBound(object sender, EventArgs e)
{
DropDownList ddlType = null;
if (FormView1.Row != null)
{
ddlType = (DropDownList)FormView1.Row.FindControl("ddlType");
}
}
Upvotes: 0
Views: 2364
Reputation: 1081
I Was not checking that Formview1.Row is null or not. Here is the solution:
protected void FormView1_DataBound(object sender, EventArgs e)
{
DropDownList ddlType = null;
if (FormView1.Row != null)
{
ddlType = (DropDownList)FormView1.Row.FindControl("ddlType");
}
}
Upvotes: 2
Reputation: 63
Here's an extension method, which allows to search recursive. It extends your current constrols with the method 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;
}
}
Upvotes: 2