Alessandro Minneci
Alessandro Minneci

Reputation: 301

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

Upvotes: 1

Views: 558

Answers (1)

JKerny
JKerny

Reputation: 548

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");

Upvotes: 1

Related Questions