I have a problem about findControl method in naming container. It's not the first trouble about that and I would like understand the theory. I found many solutions on website but nothing works
I have a DetailsView which contains controls. I put DefaultMode "Insert" and I add 2 radio buttons
<asp:DetailsView ID="DetailsView1" runat="server"
ItemType="[...]"
DefaultMode="Insert"
[...]">
<Fields>
<asp:TemplateField>
<InsertItemTemplate>
<asp:Panel ID="Panel1" runat="server" GroupingText="Create or Select">
<div class="Select">
<asp:RadioButton ID="RB_Select" runat="server" Text="Select" Checked="True" AutoPostBack="true" OnCheckedChanged ="RB_Select_CheckedChanged" />
<asp:DropDownList runat="server" ID="DDL_Select"
ItemType="[...]"
[...]
AutoPostBack="true">
</asp:DropDownList>
</div>
<div class="New">
<asp:RadioButton ID="RB_New" runat="server" Text="New" Checked="false" AutoPostBack="true" OnCheckedChanged="RB_New_CheckedChanged" />
<asp:TextBox ID="TXB_New" runat="server" Enabled="false" Text="<%# BindItem.Label %>"></asp:TextBox>
</div>
</asp:Panel>
</InsertItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
And for exemple in my behind Code, I Just want to test if radiobutton is check or not :
protected void RB_New_CheckedChanged(object sender, EventArgs e)
{
var RadioButtonNew = (RadioButton)FindControl("RB_New");
var RadioButtonSelect = (RadioButton)FindControl("RB_Select");
RadioButtonSelect.Checked = !RadioButtonNew.Checked;
}
And I have a "System.NullReferenceException" because it doesn't find my controls.
Why it doesn't recognize my controls? And how to deal with this?
Thanks in advance
You are using FindControl
on a Page level. But the Controls are inside a DetailsView, so you need to access that first.
TextBox tb = DetailsView1.FindControl("TXB_New") as TextBox;
//or
var RadioButtonSelect = (RadioButton)DetailsView1.FindControl("RB_Select");
Thank you again, I found the solution.
I didn't know but Panel element acted like a container. I just add a findControl :
var RadioButtonSelect = (RadioButton)DetailsView1.FindControl("Panel1").FindControl("RB_Select");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.