Click here to Skip to main content
Click here to Skip to main content

How to get Hidden Column Value in GridView

By , 12 May 2010
 
Suppose I want to display Address details in GridView but don't want to display AddressId then I will hide column that displays AddressId. GridView has CheckBox also to select Addresses. Now at runtime on click of button I want to get AddressId of all selected Addresses in that case if I use gvAddress.Rows[index].Cell[1] to get AddressId it will return Nothing.
 
The reason behind is, if Gridview has any BoundField column for which visible property is set to "false" then that columns is not rendered at runtime in GridView and data of hidden column won’t be available .
 
But, there are four other ways to get value of hidden column.
 
1. First Way - Use DataKeyNames Property of GridView
 

(a). GridView has property named "DataKeyNames". DataKeyNames is used to specify Primary key coulmn(s) of the data source that is bound to the GridView. More than one primary key fields can be set to DataKeyNames. All primary key fields name must be separated by comma. When DataKeyNames property of GridView is set then values of specified columns are stored in DataKeys collection that is available at runtime.
 
So, in following example to get AddressId of all selected Addresses set DataKeyNames property of GridView to "AddressID".
 
<asp:GridView ID="gvAddress" runat="server" AllowPaging="True"
             AllowSorting="True" AutoGenerateColumns="False" DataKeyNames = "AddressID"
             DataSourceID="SqlDataSource1">
             <Columns>
            <asp:TemplateField ShowHeader="false">
                <ItemTemplate>
                       <asp:CheckBox ID = "chkSelect" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
 
            <asp:BoundField DataField="AddressID" HeaderText="AddressID"
                     Visible="False" />
            <asp:BoundField DataField="AddressLine1" HeaderText="Address Line1"
                     SortExpression="AddressLine1" />
            <asp:BoundField DataField="AddressLine2" HeaderText="Address Line2"
                     SortExpression="AddressLine2" />
                              </Columns>
</asp:GridView>
 

<!-- DataSource that is bound to GridView -->
 
<SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
            SelectCommand="SELECT AddressID, AddressLine1, AddressLine2, City, PostalCode FROM Person.Address">
</asp:SqlDataSource>
 
<!-- On Click of Select button get AddressId of all selected Addresses by using different ways  -->
 
<asp:Button ID="btnSelect" runat="server" onclick="btnSelect_Click"
             Text="Select" />
 
(b). On click of button use DataKeys property of GridView to get AddressId of all selected Addressed.
 
protected void btnSelect_Click(object sender, EventArgs e)
{
    // Create a list to store selected AddressId
    List<int> lstAddressId = new List<int>();
    Control chkSelect = null;
    for (int iRow = 0; iRow &amp;lt; gvAddress.Rows.Count; iRow++)
    {
        //Find CheckBox control in GridView
        chkSelect = gvAddress.Rows[iRow].Cells[0].FindControl("chkSelect&amp");
        if (chkSelect != null)
        {
          //If CheckBox is checked then get AddressId by using DataKeys
          // properties of GridView and add AddressId of selected row in List.
          if (((CheckBox)chkSelect).Checked)
          {
              int iAddressId = (int) gvAddress.DataKeys[iRow].Value;
              lstAddressId.Add(iAddressId);
          }
        }
     }
}
 
2. Second Way - Use TemplateField column in GridView

 
(a). Create TemplateField column for hidden column in GridView, add Label control inside ItemTemplate And set visible to false for <asp:templatefield xmlns:asp="#unknown">. So that TemplateField column won't be displayed at runtime. Value of label can be accessed at runtime by using Label's Text property.
 
<asp:GridView ID="gvAddress" runat="server" AutoGenerateColumns="False" >
  <columns>
      <asp:TemplateField ShowHeader="false">
          <ItemTemplate>
             <asp:CheckBox ID = "chkSelect" runat="server" />
          </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField Visible=false>
         <ItemTemplate>
             <asp:Label id="lblAddressId" runat ="server" text='<%# Eval("AddressID")%>'>
         </ItemTemplate>
      </asp:TemplateField>
      <asp:BoundField DataField="AddressLine1" HeaderText="AddressLine1" SortExpression="AddressLine1" />
      <asp:BoundField DataField="AddressLine2" HeaderText="AddressLine2" SortExpression="AddressLine2" />
  </columns>
<asp:GridView>
 
(b). Use FindControl method of Row property of GridView to find Label control defined inside TemplateField column and assign it to label object and get value of label by using text property.
 
protected void btnSelect_Click(object sender, EventArgs e)
{
         // Create a List of Integer to store selected AddressId
         List<int> lstAddressId = new List<int>();
         Label lblAddressId = null;
         Control chkSelect = null;
         for (int iRow = 0; iRow &lt; gvAddress.Rows.Count; iRow++)
         {
             //Find CheckBox control in GridView for particular Row
            chkSelect = gvAddress.Rows[iRow].Cells[0].FindControl("chkSelect");
            if (chkSelect != null)
            {
                //If CheckBox is checked means Row is selected then  
                //find Label ”lblAddressId” that 
                //is inside TemplateField in GridView and add 
                //AddressId of selected row in List 
                //by using Label’s Text property.
                if (((CheckBox)chkSelect).Checked)
                {
                     lblAddressId =  (Label)GVAddress.Row[iRow].FindControl("lblAddressId");
                     if (lblAddressId != null)
                     {
                         int iAddressId = (int)  lblAddressId.Text;
                         lstAddressId.Add(iAddressId);
                     }
                }
         }
}
 
3. Third Way - Use StyleSheet
 

(a). Create a stylesheet for hiding grid column.
 

<style type=”text/css”>
    .hideGridColumn
    {
        display:none;
    }
 </style>
 

(b). Set HeaderStyle-CssClass and ItemStyle-CssClass property of column to hideGridColumn, that is defined in css, to hide column.
 

<asp:GridView ID="gvAddress" runat="server" AllowPaging="True"
             AllowSorting="True" AutoGenerateColumns="False"
             DataSourceID="SqlDataSource1">
             <Columns>
                  <asp:TemplateField ShowHeader="false">
                      <ItemTemplate>
                            <asp:CheckBox ID = "chkSelect" runat="server" />
                     </ItemTemplate>
                  </asp:TemplateField>
 
                 <asp:BoundField DataField="AddressID" HeaderText="AddressID" HeaderStyle-CssClass = "hideGridColumn" ItemStyle-CssClass="hideGridColumn"/>
                 <asp:BoundField DataField="AddressLine1" HeaderText="Address Line1"
                     SortExpression="AddressLine1" />
                 <asp:BoundField DataField="AddressLine2" HeaderText="Address Line2"
                     SortExpression="AddressLine2" />
             </Columns>
         </asp:GridView>
 
(c). Get value of hidden column i.e. "AddressId" by using gvAddress.Rows[iRow].Cells[1].Text property.
 
protected void btnSelect_Click(object sender, EventArgs e)
{
        // Create a List of Integer to store selected AddressId
        List<int> lstAddressId = new List<int>();
        Control chkSelect = null;
        for (int iRow = 0; iRow &lt; gvAddress.Rows.Count; iRow++)
        {
            //Find CheckBox control in GridView
            chkSelect = gvAddress.Rows[iRow].Cells[0].FindControl("chkSelect");
            if (chkSelect != null)
            {
                //If CheckBox is checked then add AddressId of selected row in List by using
                // gvAddress.Rows[iRow].Cells[1].Text property
                if (((CheckBox)chkSelect).Checked)
                {
                    int iAddressId = (int)gvAddress.Rows[iRow].Cells[1].Text;
                    lstAddressId.Add(iAddressId);
                }
             }
}
 

4. Fourth Way - Set Visibility of Column after Binding DataSource to GridView
 

Set column's visible property to false that is required to hide after binding Data Source to Gridview in Codebehind. In that case value of hidden column can be get by using "GVAddress.Rows[iRow].Cell[1].Text" as shown in the example of Third Way.
 

// Bind GridView to Data Source
GVAddress.DataSource = dtAddress;
GVAddress.DataBind();
//Set visible to false for AddressId column after binding
//Data Source to GridView
GVAddress.Columns[1].Visible = false;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Nidhi P Bhargava
Software Developer (Senior)
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralHi!, I have a gridview that has a button inside the ItemTemp...memberjusticet23 Nov '11 - 19:34 
Hi!, I have a gridview that has a button inside the ItemTemplate. I need to be able to select any record and get the ID of such record, my Datakeys is ID.
 
I have the following code that I am using to fetch the id from the gridview:
 
dim idNo as Integer = gvCust.selectedindex
idNo = gvCust.datakeys(0).value
 
this code only gives me the id of the first row even when i select the second row.
GeneralThird waymemberaul_aya17 Aug '10 - 20:01 
I prefer to use the third way,,
It's simple and works just fine..Thanks...Thumbs Up | :thumbsup:

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 13 May 2010
Article Copyright 2010 by Nidhi P Bhargava
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid