How to get selected value from gridview row in ASP.Net using C#

In this post, I would like to share how to get selected value from gridview row in ASP.Net using C#. I posted already how to binding data into gridview from database. This example, I have a gridview and three label. When I click on select in gridview, the values of the gridview row will be display on the labels. Please examine sample code below:

Code Design : 


<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br/>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br/>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label><br/>
<br/><br/><br/><br/>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="userid" onselectedindexchanged="GridView1_SelectedIndexChanged"
CellPadding="4" ForeColor="#333333" GridLines="None" >

<AlternatingRowStyle BackColor="White"/>
<Columns>
   <asp:CommandField ShowSelectButton="true"/>
   <asp:BoundField DataField="userid" HeaderText="User ID" SortExpression="userid"/>
   <asp:BoundField DataField="name" HeaderText="Name" SortExpression="name"/>
   <asp:BoundField DataField="position" HeaderText="Position" SortExpression="position"/>
</Columns>
<EditRowStyle BackColor="#2461BF"/>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White"/>
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White"/>
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center"/>
<RowStyle BackColor="#EFF3FB"/>
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333"/>
<SortedAscendingCellStyle BackColor="#F5F7FB"/>
<SortedAscendingHeaderStyle BackColor="#6D95E1"/>
<SortedDescendingCellStyle BackColor="#E9EBEF"/>
<SortedDescendingHeaderStyle BackColor="#4870BE"/>
</asp:GridView> 


Code Behind : 
protectedvoid GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow gv = GridView1.SelectedRow as GridViewRow;
     Label1.Text = gv.Cells[1].Text;
     Label2.Text = gv.Cells[2].Text;
     Label3.Text = gv.Cells[3].Text; 
 }

Done ...Hope this post is useful for you.

How to get selected value from gridview row in ASP.Net using C# How to get selected value from gridview row in ASP.Net using C# Reviewed by BeiLover on 3:10 PM Rating: 5

No comments:

Powered by Blogger.