我在formview中有一个编辑按钮和一个下拉列表。我正在使用Linq To Entities来获取我需要使用的数据,并且填充和查看formview itemtemplate没有问题。
但是,下拉列表控件(id="ddlEligibility"
)仅在edititemtemplate
中(我使用itemtemplate
中的文本框来显示当前值)并且我遇到了绑定此问题的问题控制数据源。
具体来说,当我点击“编辑”按钮时,我会在下面的最后一行代码中获得NullReferenceException - "Object not set to an instance of an object"
。有谁知道我做错了什么?
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";
}
}
FormView中的DropDownlist ...
<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>
更新: 我尝试在下面的链接(对于FormView)中接受的答案中讨论的FindControlRecursive方法,看看是否由于某种原因控件不在我认为的地方但仍然没有运气,它总是返回null。当我在页面上查看源代码时,控件“ddlEligibility”就在那里。
ASP.net .FindControl() and GridView returning null
新更新 我能够通过添加fvSubsriber.databind()来找到控件,如上面的代码所示,但是我无法获得edititemtemplate来显示itemtemplate中显示的下拉列表中的值。在edititemtemplate中,默认为dropdownlist中的第一项。我已经添加了上面的代码。我已将此新问题移至新帖子
答案 0 :(得分:0)
您可以尝试这样做,在提供数据源之前执行检查
var ddlEligibility = ((DropDownList)(fvSubscriber.FindControl("ddlEligibility")));
if(ddlEligibility!=null)
{
ddlEligibility.DataSource = program;
ddlEligibility.DataBind();
}
else
{
statusMesage.InnerHtml = "IT IS NULL";
}