Reputation: 1394
I am confused with this problem.
I have put a button in side the template field of a gridview and want to return the data from that specific GridView Row when that corresponding button is clicked.
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button2" CssClass ="btnSkin" runat="server" Text="Answer" Width="117px" onclick="Button2_Click" />
</ItemTemplate>
</asp:TemplateField>
In the button click event fireup, I want to read that data by creating a GridViewRow Element.
protected void Button2_Click(object sender, EventArgs e)
{
GridViewRow gvr = (GridViewRow)(sender as Control).Parent.Parent;
Label8.Text = gvr.Cells[1].Text;
Label10.Text = gvr.Cells[2].Text;
Label12.Text = gvr.Cells[3].Text;
}
Now the problem is, the GridViewRow Cells are returning empty strings.
What should I do?????
Upvotes: 3
Views: 4278
Reputation: 1394
I found the reason behind the empty strings error.
Gridview.Cells[i].Text
will return the string value only when it is a <asp:BoundField>
If it is a <asp:TemplateField>
and you have some ASP control inside the <ItemTemplate>
, you must follow the FindControl("<control_id>")
approach.
Here, basically we look for the control object in that particular GridviewRow
Cell by its ID and cast it into the corresponding Control Type. Now, we can use that as we call any other asp control from code-behind.
String str = ((Label)gvr.Cells[1].FindControl("Label1")).Text;
Upvotes: 3
Reputation: 10565
When using <asp:TemplateFields>
, you actually need to find the text which is inside your controls such as <asp:Label>
you used inside your <ItemTemplate>
.
Cells won't have text, its the Controls inside the cells that have text.
So, If suppose , you have a Label inside one of your <ItemTemplate>
as:
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("CustomerID") %>'>
</asp:Label>
</ItemTemplate>
Then access the Text of this Label control using below code in your button Click event:[ assuming, 2nd Column contains the above <ItemTemplate>
defined ]
protected void Button2_Click(object sender, EventArgs e)
{
GridViewRow gvr = (GridViewRow)(sender as Control).Parent.Parent;
String str = ((Label)gvr.Cells[1].FindControl("Label1")).Text;
}
Upvotes: 3
Reputation: 4753
Please check whether you are binding the grid properly on Page Load.
if(!IsPostBack)
{
BindgridView();
}
Hope this helps..Give a try..
Upvotes: 0
Reputation: 4354
Try using GridView.RowCommand Event and refer the following link for the same
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx
hope this helps you.
Upvotes: 1