Dynamic Access to controls in DetailsView

Source: Internet
Author: User
The DetailsView control is used for the project. In EditItemTemplate, You need to initialize a DropDownList data. I tried to use the FindControl method in the ModeChanging or ModeChanged event of the DetailsView control to obtain access to the target control, but all failed.

I used the DropDownList_DataBinding event to solve the problem. I added the onDataBinding event command to the DropDownList IN THE TemplateField OF THE DetailsView control. Then it will be okay to process this event in cs.

The code in aspx of DetailsView is as follows (data source code is omitted ):

1 <asp: DetailsView ID = "DetailsView1" DataKeyNames = "ClassID"
2 runat = "server" DataSourceID = "SqlDataSource1" AutoGenerateRows = "False">
3 <Fields>
4 <asp: BoundField HeaderText = "category name" DataField = "ClassTitle"/>
5 <asp: TemplateField HeaderText = "category">
6 <ItemTemplate>
7 <% # Eval ("ParentTitle") %>
8 </ItemTemplate>
9 <EditItemTemplate>
10 <asp: DropDownList ID = "ddlParent" runat = "server" onDataBinding = "ddlParent_DataBinding">
11 </asp: DropDownList>
12 </EditItemTemplate>
13 </asp: TemplateField>
14 <asp: CommandField ShowEditButton = "True"/>
15 </Fields>
16 </asp: DetailsView>

Cs file:
1 protected void ddlParent_DataBinding (object sender, EventArgs e)
2 {
3 // Add data binding code
4 // BindDropDownList (DropDownList) sender );
5}

Note:

The failure is because it is too early to call the FindControl method. You have to do this in the ItemCreated event or PreRender event of DetailsView.

Protected void DetailsView1_PreRender (object sender, EventArgs e)
{
If (IsPostBack)
{
DetailsView detailsView = (DetailsView) sender;
If (detailsView. CurrentMode = DetailsViewMode. Edit)
{
DropDownList dropDownList = (DropDownList) detailsView. FindControl ("DropDownList1 ");
DropDownList. Items. Add (new ListItem ("text", "value "));
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.