Steven Armstrong
Steven Armstrong

Reputation: 47

ASP.NET - How to find a control in ListView from a dropdown list SelectMethod attribute

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 ?

Upvotes: 0

Views: 1024

Answers (2)

Steven Armstrong
Steven Armstrong

Reputation: 47

Just add OnDataBound attribute to DropDownList and write this method for the OnDataBound event:

C#:

        protected void DropDownList1_DataBound(object sender, EventArgs e)
            {
                var control = (Control)sender;
                var lvi = (ListViewItem)control.NamingContainer;
                var label = (Label)lvi.FindControl("LabelCategoryId");
                string text = label.Text;
                var ddl = (DropDownList)sender;
                ddl.SelectedValue = text;
            }

This will change the SelectedValue of the DropDownList according to the label text of each item in the ListView.

Upvotes: 1

AT-2017
AT-2017

Reputation: 3149

You need to iterate a loop to get the label value as follows:

foreach (ListViewItem item in ListView1.Items)
{
    Label mylabel = (Label)item.FindControl("Label1");
    lblID.Text = mylabel.Text;
}

Note: This will do for other controls as well.

If it doesn't work, there is another solution. Do the following:

ListViewItem item = ListView1.Items[ListView1.SelectedIndex];  
Label myLabel = (Label)item.FindControl("Label1");

string result = myLabel.text; //Get the text here

Upvotes: 1

Related Questions