How to get value from HiddenField within Gridview in ASP.Net using C#

This post will guide you how to get value from hiddenfield within gridview in asp.net. In this example, I have a button and a gridview with a checkbox, a hiddenfield  and a boundfield. I want to get value row that i checked on checkbox when I click on a button. Please look at code below:
Code Design :

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
  <Columns>
    <asp:TemplateField HeaderText="Select">
       <ItemTemplate>
         <asp:CheckBox ID="chkBxSelect" runat="server" AutoPostBack="true"/>
       </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
       <ItemTemplate>
          <asp:HiddenField ID="Invoice_ID" runat="server" Value='<%#Eval("Invoice_ID")%>'/>
       </ItemTemplate>
    </asp:TemplateField>
   <asp:BoundField DataField="Invoice" HeaderText="Invoice" SortExpression="Invoice" />
 </Columns>
</asp:GridView>


<asp:Button ID="Button1" runat="server" Text="Search" Width="80px" Height="25px" onclick="Button1_Click"/>

 Code Behind : 

protected void Button1_Click(object sender, EventArgs e)
{
   string invoiceID="";
   string invoice="";
   string message="";

for (int k = 0; k < GridView1.Rows.Count; k++)
 {
   //declare checkbox 
   CheckBox chk = (CheckBox)GridView1.Rows[k].FindControl("chkBxSelect");
   if (chk.Checked == true)
   {
    //The first or only a checkbox is checked
     if (k==0)
     {
        //get value from hiddenfield
         invoiceID = ((HiddenField)GridView1.Rows[k].Cells[1].FindControl("Invoice_ID")).Value;
        //get value from boundfied                      
        invoice= GridView1.Rows[k].Cells[2].Text;
      }     
       //the next checkboxs are checked
      else
      {
        invoiceID += "," +
((HiddenField)GridView1.Rows[k].Cells[1].FindControl("Invoice_ID")).Value;
        invoice += "," + GridView1.Rows[k].Cells[2].Text;
      }
    }    
    //if no checkboxs is checked
    else
    {
       //display message from page
       message = "Please check on checkbox to get value";
       Page.ClientScript.RegisterStartupScript(Page.GetType(), "shwomessage", "alert('" + message + "');", true);
     } 
    }
}
Done .....Hope this post will help you.
How to get value from HiddenField within Gridview in ASP.Net using C# How to get value from HiddenField within Gridview in ASP.Net  using C# Reviewed by BeiLover on 1:45 PM Rating: 5

No comments:

Powered by Blogger.