Alessandro Minneci Alessandro Minneci - 1 year ago 98
ASP.NET (C#) Question

Call TemplateField DropDownList in asp.net - code behind with FindControl()

This is how i created my

DropDownListLehrbeginn
in my GridView. sss

<asp:TemplateField HeaderText="Lehrbeginn" SortExpression="lehrbeginn" HeaderStyle-Width="40px">
<EditItemTemplate>
<asp:DropDownList ID="DropDownListLehrbeginn" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelLehrbeginn" runat="server" Text='<%# Bind("lehrbeginn") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>


I want to add ListItems with c# like this:

DropDownListLehrbeginn.Items.Add(new ListItem(DateTime.Now.Year.ToString()));
DropDownListLehrbeginn.Items.Add(new ListItem(DateTime.Now.AddYears(1).Year.ToString()));
DropDownListLehrbeginn.Items.Add(new ListItem(DateTime.Now.AddYears(2).Year.ToString()));
DropDownListLehrbeginn.Items[1].Selected = true;


It doesnt work unfortunately. How can i fix this issue?
DropDownListLehrbeginn
is not available in code behind

Answer Source

Your code looks fine. Because your drop down list is within another element you probably just need to use something like this

DropDownList ddlList = (DropDownList)NameOfGridView.FindControl("DropDownListLehrbeginn");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download