I have a FormView and I need to access some Divs and other controls that are inside it. My apsx code looks similar to this:
<asp:FormView ID="Edit_FV" runat="server" DataKeyNames="IDproceso" DefaultMode="Edit" DataSourceID="SqlDS_Procesos">
<EditItemTemplate>
<div id="second_info" runat="server">
<div id="second_info_left" runat="server">
<div id="alcance" class="report_field" runat="server">
<p class="container-title">
Alcance:</p>
<asp:TextBox ID="TextBox14" runat="server" TextMode="multiline" Width="400px" Height="120px" Text='<%# Bind("alcance") %>' />
</div>
</div>
<div id="second_info_right" runat="server">
<div class="valores-container" id="tipo_ahorro" runat="server">
<asp:CheckBox ID="ahorro_state" runat="server" Checked='<%# Bind("tipo_ahorro") %>' />
</div>
</div>
</EditItemTemplate>
</asp:FormView>
Now, say I want to access the CheckBox with id = ahorro_state, I tried with Edit_FV.FindControl("ahorro_state") and got a Null reference. I also tried with Edit_FV.FindControl("MainContent_Edit_FV_ahorro_state") because this is how the ID actually gets named in the final HTML document, but I got a Null reference too. The same happened when I tried accessing any of the divs (with IDs second_info,tipo_ahorro, etc..). I feel I’m doing a dumb mistake but I looked around a bit and haven’t found and answer.
Any ideas how to solve this?
EDIT: Added Code where I’m calling FindControl.
I tried both calling DataBind() from the Page_Load():
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
if (Edit_FV.CurrentMode == FormViewMode.Edit)
{
Control c = Edit_FV.FindControl("ahorro_state");//c is null here.
}
}
And also tried setting the OnDataBound attribute of Edit_FV: OnDataBound="onBound"
protected void onBound(object sender, EventArgs e)
{
if (Edit_FV.CurrentMode == FormViewMode.Edit)
{
ControlCollection a = Edit_FV.Controls;
Control c = Edit_FV.FindControl("ahorro_state");//c is null here
}
}
Although the default mode is set “Edit”, the form view won’t switch to that mode until the control is DataBound. Try calling
DataBind()first, then use FindControl using the ID of your element (not the ClientID, as you tried in your second example).See FormView.FindControl(): object reference error for examples of where to put your FindControl logic.
EDIT:
There is also the possibility that your data source is not returning any data. This will result in the EditItemTemplate being empty which might explain your null reference errors. Try checking for a
Edit_FV.DataItemCount > 0before switching into Edit mode.