FindControl (ImageButton) inside a ListView
I hope someone could help me with this. I wasn't able to find the ImageButton control inside the ListView, it always gives me Object reference not set to an instance of an object error.
The scenario is, if I checked the checkbox, I wanted the imagebutton to change its' image. The Checkbox does not reside inside the Listview ItemTemplate. Here's my code behind for the checkbox_checkchanged event:
if (cb.Checked)
{
foreach (Control c in lv.Controls)
{
ImageButton btndel = (ImageButton)c.FindControl("btnDelete");
btndel.ImageUrl = "~/images/activate.png";
}
}
Note: I used ForEach Loop thinking that the btnDelete button appears several times in my L开发者_运维知识库istview.
If the Checkbox is outside of the ListView, the best way would be to use ListView's ItemCreated-Event:
protected void LV_ItemCreated(object sender, ListViewItemEventArgs e)
{
// Retrieve the current item.
ListViewItem item = e.Item;
// Verify if the item is a data item.
if (item.ItemType == ListViewItemType.DataItem && cb.Checked)
{
ImageButton btndel = (ImageButton)item.FindControl("btnDelete");
btndel.ImageUrl = "~/images/activate.png";
}
}
You don't need to handle the Checkbox' CheckedChanged-Event but only need to add the OnItemCreated-handler on your aspx markup:
<asp:ListView ID="LV" OnItemCreated="LV_ItemCreated" ... />
On this way you prevent multiple iterations of the ListView-Items. ItemCreated will anyway be called implicitely on every postback to recreate the ListView-Items.
before casting you should check if the result of FindControl is null or of proper type.
Try to call FindControl also inside the Controls of the c
object because it could be the control you are looking for is down one more level of nesting ( so inside the ListViewItem ), actually, you can loop inside the lv.Items
and do a FindControl in there...
For each (ListViewDataItem c in lv.items)...
精彩评论