gkrishy
gkrishy

Reputation: 756

How to retrieve a datalist item in c#?

My Source page :

  <asp:DataList ID="datalist" RepeatColumns="6" runat="server" > 
  <ItemTemplate>
  <div class="rating">
  <div>
  <cc1:Rating ID="Rating1" AutoPostBack="true" OnChanged= "rt_chnaged" runat="server" StarCssClass="ratingstar"  RatingAlign="Horizontal"  WaitingStarCssClass="ratingSaved" EmptyStarCssClass="ratingEmpty" FilledStarCssClass="ratingFilled">
                 </cc1:Rating>  </div>
  <asp:Label runat="server"  ID="Label2" Text='<%# Eval("moviename") %>' Visible="true"></asp:Label>
  </div>
  </ItemTemplate></asp:DataList>

My Code Behind :

 public void rt_chnaged(object sender, AjaxControlToolkit.RatingEventArgs e)
 {
    Label lbl = null;
    foreach (DataListItem li in datalist.Items)
    { 
       lbl = li.FindControl("Label2") as Label;
    }
    Label3.Text = lbl.Text;
 }

Here My question is simple, but I'm struggling more by spending lot of hours to solve this.

In this, I bound everything from database. What exactly i want is, on clicking of respective rating bar, i need to display the respective movie name in outside of the label i.e., Label3.

For eg:

Consider am having Transformers, Planet of the Apes and Mankatha in moviename column(Database). So here my output will be three label with three rating bar. So what i want now is, simply i need to display the movie name in label2(inside of datalist) to label3(Outside of datalist)

Here I tried with my code(Mentioned few lines before), but always am getting only Mankatha, because of for each. I can understand the reason, but am struggling to find out the solution.

please someone help me to over come the issue. Thanks in advance.

Upvotes: 2

Views: 2463

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460208

You can use the NamingContainer of a control in the item (works also for other databound webcontrols like repeater or gridview).

The sender is always the control that raised an event, in this case the Rating control:

public void rt_chnaged(object sender, AjaxControlToolkit.RatingEventArgs e)
{
    Rating rating = (Rating) sender;
    DataListItem item = (DataListItem) rating.NamingContainer;
    Label lbl = (Label) item.FindControl("Label2");
    Label3.Text = lbl.Text;
}

Upvotes: 2

Related Questions