Vinz' Blog

"Code, Beer and Music" ~ my way of being a programmer!
posts - 124, comments - 367, trackbacks - 0

My Links

News

Archives

Image Galleries

FAQ: How to Get Hidden Column values in GridView

I decided to write this simple demo because this issue has been asked many times at the forums.

Hidden columns are fields in GridView that you don’t want to expose or show in the page, usually this field is the primary key of the data. Since a primary is a confidential data then you might want to hide it to the users. Most people usually use BoundField columns for displaying the data and just hide the field that contains the primary key.

In this example, I will demonstrate two ways on how to access hidden columns when a specific row is selected in GridView.

To get started, let’s grab a GridView control from the Visual Studio toolbox, and then drop it at the Webform.

Binding the GridView with data:

Note that I did not use a database here for populating the GridView with data. Just for the simplicity of this demo, I just use a dummy data for populating the GridView using the DataTable object.

Here’s the code block below:

 

private void BindGrid()

{

        DataTable dt = new DataTable();

        DataRow dr = null;

        dt.Columns.Add(new DataColumn("Column1", typeof(string)));

        dt.Columns.Add(new DataColumn("Column2", typeof(string)));

        dr = dt.NewRow();

        dr["Column1"] = "1";

        dr["Column2"] = "Sample A";

        dt.Rows.Add(dr);

        dr = dt.NewRow();

        dr["Column1"] = "2";

        dr["Column2"] = "Sample B";

        dt.Rows.Add(dr);

        dr = dt.NewRow();

        dr["Column1"] = "3";

        dr["Column2"] = "Sample C";

        dt.Rows.Add(dr);

 

        GridView1.DataSource = dt;

        GridView1.DataBind();

 

}

 

Now let’s, call the method above on initial load:

 

protected void Page_Load(object sender, EventArgs e)

{

        if (!Page.IsPostBack)

        {

            BindGrid();

        }

}

 

Now let’s set up the columns in the GridView for displaying the corresponding data. The GridView ASPX source should look something like this:

 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

        onselectedindexchanged="GridView1_SelectedIndexChanged">

    <Columns>

    <asp:CommandField ShowSelectButton="True" />

    <asp:BoundField HeaderText="Header 1"  DataField="Column1" Visible="false" />

    <asp:BoundField HeaderText="Header 2"  DataField="Column2" />

    </Columns>

</asp:GridView>

 

As you noticed, the Visibility of the BoundField column that holds the Column1 data was set to FALSE means that field is hidden/invisible.

 

Note: Column1 serves as the primary key column in this example.

 

Let’s try to access the value of the hidden column when selecting a specific row in the GridView. To do this, we can use the SelectedIndexChanged event of GridView.

 

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

{

        string strValue = GridView1.SelectedRow.Cells[1].Text;

 

        //display the selected value in a pop up

        Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "SCRIPT", string.Format("alert('{0}');", strValue), true);

       

}

 

Running the codes above will give you an empty value when you select a row in the GridView.

 

Why?

This is because, for security reasons BoundField columns with Visibility set to FALSE  will not be rendered the page and thus we cannot directly get the value in our codes.

The workarounds:

Option1: Using the DataKeyNames of GridView (recommended)

The easiest way to store the hidden fields (primary keys) is by using DataKeyNames property of the GridView control because this provides a convenient way to access the primary keys of each row.

Here are the code blocks below:

 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Column1"

        onselectedindexchanged="GridView1_SelectedIndexChanged">

    <Columns>

        <asp:CommandField ShowSelectButton="True" />

        <asp:BoundField HeaderText="Header 2"  DataField="Column2" />

    </Columns>

</asp:GridView>

 

As you can see, we removed the hidden BoundField column that contains the Column1 data in the GridView and set up the DataKeyNames in the GridView instead.

Here’s the code for accessing the primary key of the row using the DataKeys.

 

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

{

   //get the selected DataKey

   int rowIndex = GridView1.SelectedIndex;

   string strValue = GridView1.DataKeys[rowIndex].Value.ToString();

 

   //display the selected value in a pop up

   Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "SCRIPT", string.Format("alert('{0}');", strValue), true);

}

 

Option 2: Using a TemplateField Column with a HiddenField Control

Another way would be storing the primary key column in a HiddenField Control.

Here’s an example:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

        onselectedindexchanged="GridView1_SelectedIndexChanged">

    <Columns>

        <asp:CommandField ShowSelectButton="True" />

        <asp:TemplateField>

        <ItemTemplate>

            <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Bind("Column1") %>' />

        </ItemTemplate>

        </asp:TemplateField>

        <asp:BoundField HeaderText="Header 2"  DataField="Column2" />

    </Columns>

</asp:GridView>

 

Now here’s the relevant code for accessing the primary key data that was stored in a HiddenField control:

 

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

{

        string strValue = ((HiddenField)GridView1.SelectedRow.Cells[1].FindControl("HiddenField1")).Value;

 

        //display the selected value in a pop up

        Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "SCRIPT", string.Format("alert('{0}');", strValue), true);

    }

 

That’s it! Hope you will find this example useful!

Print | posted on Monday, June 22, 2009 5:57 AM |

Feedback

Gravatar

# re: FAQ: How to Get Hidden Column values in GridView

I gone through the code, but in my case it will not work as I have to hide two fields and like to retieive two values each time a user click on select option given in the grid.

Can u give me a customized example.
8/11/2009 6:46 PM | jay Khatri
Gravatar

# re: FAQ: How to Get Hidden Column values in GridView

@Jay,

if you wan't to hide two columns then you can set multiple columns in the DataKeyNames like:

DataKeyNames="Column1, Column2"

then you can access it this way:

string key1 = GridView1.DataKeys[rowIndex].Values[0].ToString(); //first key
string key1 = GridView1.DataKeys[rowIndex].Values[1].ToString(); //first key
8/11/2009 8:27 PM | Vinz
Gravatar

# re: FAQ: How to Get Hidden Column values in GridView

Thanks for this! It was exactly what I was looking for.
10/21/2009 1:01 AM | Nicholus Ives
Gravatar

# re: FAQ: How to Get Hidden Column values in GridView

if i set column of gridview visible = true
with code line

GridView1.Rows(i).Cells(0).Text

i get value ok, but if i set column visible = false

i dont get value with code line above

can you help me?


http://taphop.net
11/9/2009 7:13 PM | Jonathan Nguyen
Gravatar

# re: FAQ: How to Get Hidden Column values in GridView

@Jonathan

This is because, for security reasons BoundField columns with Visibility set to FALSE will not be rendered the page and thus we cannot directly get the value in our codes.

Please review the work around mentioned in this example for a possible solution.
11/9/2009 8:19 PM | Vinz
Gravatar

# re: FAQ: How to Get Hidden Column values in GridView

Excellent!!
This is exactly what I was searching..
Thanks..
11/21/2009 11:27 PM | Savan Thakkar
Gravatar

# re: FAQ: How to Get Hidden Column values in GridView

Thanks for this explanation - it was exactly what I needed.
11/23/2009 6:56 AM | Scott
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: