Click here to Skip to main content
15,881,715 members
Articles / Web Development / ASP.NET
Tip/Trick

How to get Hidden Column Value in GridView

Rate me:
Please Sign up or sign in to vote.
4.92/5 (35 votes)
12 May 2010CPOL2 min read 282.8K   21   11
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...
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&");
        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.


CSS
<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.


XML
<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)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionthanks Pin
opc318-Sep-16 15:10
opc318-Sep-16 15:10 
QuestionThank you, really useful Pin Pin
Bogdan71f5-Apr-16 3:12
Bogdan71f5-Apr-16 3:12 
GeneralMy vote of 3 Pin
Member 1123270030-Nov-14 23:19
Member 1123270030-Nov-14 23:19 
GeneralThank you, really useful Pin
mongoose_za26-Sep-14 0:34
mongoose_za26-Sep-14 0:34 
Questiontanx Pin
R.Akhlaghi12-Aug-14 19:33
professionalR.Akhlaghi12-Aug-14 19:33 
QuestionThanks Pin
Member 892775711-Dec-13 8:05
Member 892775711-Dec-13 8:05 
GeneralMy vote of 5 Pin
Ale Urres5-Aug-13 8:19
Ale Urres5-Aug-13 8:19 
GeneralMy vote of 5 Pin
Mahesh_Bhosale16-Jul-13 21:18
Mahesh_Bhosale16-Jul-13 21:18 
Thanks
QuestionThanks Pin
Alex Ayscough14-Jun-13 4:43
Alex Ayscough14-Jun-13 4:43 
GeneralHi!, I have a gridview that has a button inside the ItemTemp... Pin
justicet23-Nov-11 19:34
justicet23-Nov-11 19:34 
GeneralThird way Pin
aul_aya17-Aug-10 20:01
aul_aya17-Aug-10 20:01 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.