views:

106

answers:

3

Structure of my asp: repeater

repeater
    updatePanel
         label1 (rating)
         button (updates rating)
         some_picture (thing being rated)
     /update panel
/repeater

Imagine the output of the above repeater containing 100 rows. (1 label, and 1 button on each row).

Goal: when I click the button, I want the appropriate label to be updated. I dont know how to do this. I can reference a label via:

Label myLabel2Update = (Label)Repeater1.Controls[0].Controls[0].FindControl("Label1");

But ofcourse, it will be the same label each time (not necessarily the label that needs to be updated). I need to update the label that is on the same row as the button.

Any guidance would be appreciated.

A: 

You will need a helper method to iterate through the hierarchy or use the Control's FindControl(string id) method for that.

Example:

var stateLabel = (Label)e.Row.FindControl("_courseStateLabel");
Markust
+1  A: 

Handle the ItemCommand event of the repeater. In your event handler check the Item property of the event arguments and use findcontrol on that. e.g.

protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    Label Label1 = (Label)e.Item.FindControl("Label1");
}

Label1 will be the label in the same item as the button that was clicked.

Or in response to Dr. Wily's Apprentice's comment you could do the following

protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    switch (e.CommandName)
    {
        case "bClick":
            Label Label1 = (Label)e.Item.FindControl("Label1");
            /*do whatever processing here*/
            break;            
    }
}

And then for each button specify the command name "bClick"

Dustin Hodges
If I'm not mistaken, you will need to ensure that the Button control specifies a value for the CommandName property in order for this ItemCommand event to be fired. Additionally, within the ItemCommand event handler you may need to check the CommandName property of the event args to make sure that you're handing the event that you think you are, just in case there is any possibility now or in the future of other buttons or links causing the ItemCommand event to fire with a different CommandName. This is a good approach, though.
Dr. Wily's Apprentice
You are correct that you should add a command name to the button so you can ensure that you are handling the correct command but an ItemCommand event will fire and you can handle it without providing a command name you just can't be sure that you are handling the right thing. I'll edit my answer.
Dustin Hodges
A: 

I assume there's an event handler for the button? If so, you should be able to do

protected virtual void OnClick(object sender, EventArgs e)
{
    var label = ((WebControl)clickedButton).Parent.FindControl("Label1");
}
Sterno