C# .NET - How to find control in gridview itemtemplate

Asked By abinav shankar on 17-Jan-12 02:14 PM
Hi
 
I want to find control of a linkbutton which is in the itemtemplate and I used the following code and i get the value but because of using the for loop I am getting only the last value and the previous values is getting cleared here is my code pl tell me how to get the correct value
<asp:TemplateField HeaderText="Associate ID">
              <ItemTemplate>
                <asp:LinkButton ID="lnkAssId" Text='<%# Eval("associate_id") %>' runat="server" 
                  onclick="lnkAssId_Click">LinkButton</asp:LinkButton>
              </ItemTemplate>
</asp:TemplateField>

for (int i = 0; i < grdApproval.Rows.Count; i++)
    {
      LinkButton lblAssId = (LinkButton)grdApproval.Rows[i].FindControl("lnkAssId");
      Session["AssId"] = lblAssId.Text;
    }
.
dipa ahuja replied to abinav shankar on 17-Jan-12 02:45 PM
void bind()
{
  foreach (GridViewRow row in GridView1.Rows)
  {
    string name = ((Label)row.FindControl("label1")).Text.ToString();
    string gender = ((DropDownList)row.FindControl("dropdown1")).SelectedValue.ToString();
    string contact = ((Label)row.FindControl("lblcontact")).Text.ToString();
 
    //code to write
  }
}
Venkat K replied to abinav shankar on 17-Jan-12 08:58 PM
If you are trying to get the reference of the LinkButton for a particular row, you need to use FindControl method without for loop but inside the RowDataBound event as shown below:

 protected void gvRatings_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label Points = ((Label)e.Row.FindControl("LabelPoints"));
//do what ever you want to do here using the value of your label
}
}

You need to concatenate the values in an array to store text for all the values:

str[] arrValues = new arrValues[20]; 

for (int i = 0; i < grdApproval.Rows.Count; i++)
{
LinkButton lblAssId = (LinkButton)grdApproval.Rows[i].FindControl("lnkAssId"); 
   arrValues[i]=lblAssId.Text;     
Session["AssId"] = arrValues[i];
}

Thanks


[)ia6l0 iii replied to abinav shankar on 17-Jan-12 10:07 PM
I don't know why you are doing this. I am not sure about its actual purpose. 

Nevertheless, you have to follow "Venkat's" reply above with a minor change: (Session should be outside the loop and should contain the entire array)

str[] arrValues = new arrValues[20]; 
for (int i = 0; i < grdApproval.Rows.Count; i++) 

LinkButton lblAssId = (LinkButton)grdApproval.Rows[i].FindControl("lnkAssId"); 
arrValues[i]=lblAssId.Text;     
}

Session["AssId"] = arrValues; 


Hope this helps.