Introduction
A beginner developer have problems with accessing to GridView Controls, why? because (for me)is hard to understand key concepts like databinding and templates. Understand really is more than read a visual studio help.
Key Concepts
Well like I said the key concepts are DataBinding and gridview's Templates
To understand DataBinding I'll prefer refer to
Templates are well explain in:
- Book ASP.NET Data Web Controls / ISBN: 0-672-32501-2/ Chapter 1
Problem
I was trying access controls inside a GridView specially when I pressed a button (ButtonField)
I have a page with this gridview:
<P> </P><P><asp:GridView ID="gvFacturas" runat="server" OnRowCommand="gvFacturas_RowCommand" </P><P>AutoGenerateColumns="False" OnRowEditing="gvFacturas_RowEditing" Width="100%"></P><P><Columns></P><P><asp:BoundField DataField="DeteOrder" DataFormatString="{0:d}" HeaderText="Date"</P><P>HtmlEncode="False" /></P><P><asp:TemplateField HeaderText="Description"></P><P><EditItemTemplate></P><P><asp:TextBox ID="txtDescription" runat="server" Text='<%# Bind("Description") %>'></P><P></asp:TextBox></P><P></EditItemTemplate></P><P><ItemTemplate></P><P><asp:Label ID="lblDescription" runat="server" Text='<%# Bind(Description")%>'></P><P></asp:Label></P><P></ItemTemplate></P><P></asp:TemplateField> </P><P><asp:ButtonField ButtonType="Image" HeaderText="Something" </P><P>ImageUrl="~/images/anular.GIF" Text="Button" CommandName="dosomething"></P><P><ItemStyle HorizontalAlign="Center" /></P><P></asp:ButtonField></P><P></Columns></P><P></asp:GridView></P><P> </P><P> </P>
As you see there are two columns types (BoundField and TemplateField)
This article is oriented to use TemplateFields, a BoundField would convert to TempleateField.
I wish to update lblDescription with another string HOW?
Solutions & Results
The "secret" is RowCommand Event and e.CommandArgument cast.
1. If you wish access and modify the grid but not affect DataSource make this:
if (e.CommandName.Equals("dosomething"))
((Label)gvGrid.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("lblDemo")).Text = "Test!"
the key is e.CommandArgument cast to int to obtain the exact row
2. If you wish modify the data behind gridview use this:
if (e.CommandName.Equals("dosomething"))
((Demo.OrderEntity)Profile.Period.Facturas[gvGrid.Rows[Convert.ToInt32(e.CommandArgument)].DataItemIndex]).Description = "Test!";
Comments?
Thanks