Mcbaloo Mcbaloo - 1 month ago 18
ASP.NET (C#) Question

How do I get the value of a particular row in my Gridview

I have a Gridview which also contains a button field. When this button on a particular row is clicked, I want it to update my database. For example, if a row contains

(SN = 1)
I want it to update the button to update the database with the row that contains
"SN = 1"
. How do I get the
SN
of the row when the button on that same row is clicked?

This is my Gridview definition:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" Height="326px" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5" style="text-align: left; margin-left: 169px" Width="1069px" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField HeaderText="S/N" DataField="SN" />
<asp:BoundField HeaderText="First Name" DataField="FirstName" />
<asp:BoundField HeaderText="Address" DataField="Address" />
<asp:BoundField HeaderText="Phone Number" DataField="PhoneNumber" />
<asp:BoundField HeaderText="Sex" DataField="Sex" />
<asp:BoundField HeaderText="Reason" DataField="Reason" />
<asp:BoundField HeaderText="SignIn" DataField="SignIn_Time" />
<asp:BoundField HeaderText="SignOut" DataField="Signout_Time" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="out" runat="server" Text="Sign out" CommandName="SignOut"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>

<PagerSettings FirstPageText="First" LastPageText="Last" Mode="NumericFirstLast" PageButtonCount="5" />
</asp:GridView>


Here, when the row button is clicked, I want to update my database with the signout time. I can't seem to get it to get the
SN
of the row and update.

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "SignOut")
{

}
}

Answer

If the value you seek is the comes from the same datasource, you can add the value as a CommandArgument:

<asp:TemplateField HeaderText="Action">
   <ItemTemplate>
       <asp:Button ID="out" 
           runat="server"
           Text="Sign out"
           CommandName="SignOut"
           CommandArgument='<%# Eval("SN") %>'/>
   </ItemTemplate>
</asp:TemplateField>

On your code behind:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "SignOut")
    {
        string sn = e.CommandArgument.ToString();
        if (sn == "1")
        {
            /*DO STUFF....*/
        }
    }
}