I have a ListView which contains a label and a dropdown list. I would like to find the label by using FindControl() from the SelectMethod attribute of the dropdown list. Here's my code:

.aspx:

<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID"
    ItemType="Models.Items" SelectMethod="GetItem">
    <ItemTemplate>
        <asp:Label ID="LabelItemId" runat="server"
            Text="<%#: Item.ID %>"></asp:Label>
        <asp:DropDownList ID="DropDownList1" runat="server" 
            SelectMethod="GetCategories" ItemType="Models.Category"
            DataValueField="CategoryID" DataTextField="CategoryName">
        </asp:DropDownList>

C#:

protected void GetCategories(object sender, ListViewItemEventArgs e)
    {
        using (var db = new ItemContext())
        {
            var dropDownList = (DropDownList)e.Item.FindControl("DropDownList1");
            IQueryable<Category> query = db.Categories;
            List<Category> categories = query.ToList();

            //The line below is the problem because e is null
            var item = categories.First(category => category.CategoryID == 
                    Convert.ToInt32(((Label)e.Item.FindControl("LabelItemId")).Text));
        }
    }

The problem is the e of ListViewItemEventArgs is null. So, I got a NullReferenceException. Maybe the reason is that I should not be using ListViewItemEventArgs for SelectMethod attribute. If that's the case, what should I use ?

Related posts

Recent Viewed