I have an edit button and a dropdownlist inside a formview. I am using Linq To Entities to get the data I need to work with and have no problem populating and viewing the formview itemtemplate.
However, the dropdownlist control (id="ddlEligibility"
) is only in theedititemtemplate
(I use a textbox in the itemtemplate
to display the current value) and I am having a problem binding this control to the datasource.
Specifically, when I click the Edit button I am getting a NullReferenceException - "Object not set to an instance of an object"
on the last line of code below. Does anyone have an idea what I am doing wrong?
protected void btnEdit_Click(object sender, EventArgs e)
{
fvSubscriber.ChangeMode(FormViewMode.Edit);
fvSubscriber.DataBind(); // Adding this line solved the first problem where I could not find the control
LifeLineDSEntities context = new LifeLineDSEntities():
var program = from p in context.EligibilityPrograms
select p;
DropDownList ddlEligibility = (DropDownList)(fvSubscriber.FindControl("ddlEligibility")));
if (ddlEligibility != null)
{
ddlEligibility.DataSource = program;
ddlEligibility.DataTextField = "ProgramName";
ddlEligibility.DataValueField = "eligibilityCode";
ddlEligibility.DataBind();
statusMessage.InnerHtml = "It is NOT null";
}
else
{
statusMessage.InnerHtml = "It is null";
}
}
DropDownlist in FormView...
<form id="form1" runat="server">
<asp:FormView ID="fvSubscriber" runat="server" RenderOuterTable="false" DefaultMode="Readonly" OnModeChanging="fvSubscriberChanging">
<ItemTemplate>
// mark up here
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlEligibility" runat="server" />
</EditItemTemplate>
</asp:FormView>
</form>
UPDATE: I tried the FindControlRecursive method discussed in the accepted answer in the link below (for FormView though) to see if for some reason the control was not where I thought it was but still no luck, it always comes back null. When I view source on the page, the control "ddlEligibility" is there.
ASP.net .FindControl() and GridView returning null
New Update I was able to find the control by adding fvSubsriber.databind() as shown in the code above, however I am unable to get the edititemtemplate to show the value in the dropdownlist that was displayed in the itemtemplate. In the edititemtemplate is just default to the first item in dropdownlist. I have added the code above. I have moved this new problem to a new post