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

Call TemplateField DropDownList in - code behind with FindControl()

This is how i created my

in my GridView. sss

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

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?
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