Geeks With Blogs

News

Microsoft MVP


DZone MVB


Moderator at CodeASP.NET


Quiz Master







free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

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!

Technorati Tags: ,,,
Posted on Monday, June 22, 2009 5:57 AM ASP.NET , C# , Tips&Tricks , GridView | Back to top


Comments on this post: FAQ: How to Get Hidden Column values in GridView

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
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.
Left by jay Khatri on Aug 11, 2009 6:46 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Thanks for this! It was exactly what I was looking for.
Left by Nicholus Ives on Oct 21, 2009 1:01 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
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
Left by Jonathan Nguyen on Nov 09, 2009 7:13 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Excellent!!
This is exactly what I was searching..
Thanks..
Left by Savan Thakkar on Nov 21, 2009 11:27 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Thanks for this explanation - it was exactly what I needed.
Left by Scott on Nov 23, 2009 6:56 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Right on! That was the silver bullet that ended my misery. ;-) Well done!
Left by Charcoal on Dec 18, 2009 11:14 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Thank you! Awesome!
Left by CS on Jan 15, 2010 8:18 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Thank you, Jonathan.
You helped me a lot.
Left by Sam on Jan 20, 2010 4:29 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Thanks a lot,
I was looking exactly the same which is explained here.

Thank you.
AKS
Left by AKS on Mar 08, 2010 12:53 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Excellent code. I helped me a lot.

EGV
Left by EGV on May 12, 2010 10:23 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Awesome, thank you!
Left by Brian on May 28, 2010 12:49 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Thank u so much. It helped me a lot...
Left by Dainy on Nov 30, 2010 3:01 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
I want to delete a row according to the hidden field value. How can i do this, please help me.
Left by CHandrakanta on Dec 02, 2010 10:31 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
@CHandrakanta,

Here are some useful examples below that you can refer:

http://geekswithblogs.net/dotNETvinz/archive/2009/02/22/gridview-insert-edit-update-and-delete--the-ado.net-way.aspx
http://geekswithblogs.net/dotNETvinz/archive/2009/06/10/adding-rows-in-gridview-with-edit-update-and-delete-functionality.aspx
Left by Vinz on Dec 03, 2010 12:05 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Thank You Very Much.
This help's me a lot....


Thank you again
Left by Tushar on Feb 28, 2011 3:19 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
For those with two columns what you can try is you can hide it on rowcreated event.
Left by gunbilegt byambadorj on Mar 01, 2011 1:23 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Thanks very much appreciated. Took me an hour and then I found this article.
Left by Will Goddard on Mar 09, 2011 5:10 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Thanks you.

I like this code from you...

<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Bind("Column1") %>' />
Left by Nguyen Thanh Hai on Apr 19, 2011 7:27 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Thanks! Now I can go to sleep!
Left by DonE on Apr 28, 2011 1:26 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Really great and hardwork......
Left by lolita on Jun 22, 2011 8:29 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Thank you!! this is perfect solution!!
Left by Naresh Reddy on Aug 10, 2011 4:42 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
The post is old I think, but it really helped me today.
Thank you so much.
Left by ali on Aug 29, 2011 10:37 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
It Helped Me a lot Thank You :)... Awesome Post :)
Left by Anis on Sep 29, 2011 2:26 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
I should say thank you coz u solved my problem.
Left by adel on Oct 02, 2011 8:57 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
It helped me a lot after working on different workarounds for a couple of hours... Thanks for that... :)
Left by Hank on Nov 03, 2011 11:46 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
The GridView1_SelectedIndexChanged event does not fire when I hit the Edit button for a GridView row, making this solution useless. I don't know why it works for you, because it doesn't for me.
Left by Hugh Mannity on Nov 07, 2011 12:01 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Option 1 FTW! Thank you!
Left by leqid on Nov 14, 2011 12:57 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Thanks man, exactly what I needed (Y)
Left by Ricardo on Nov 21, 2011 7:12 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
thank you very much, from south korea.
Left by sky on Nov 22, 2011 10:55 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Very Nice tutorial,I was stuck on this for hours...thanks...
Left by Arshad on Dec 26, 2011 6:02 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Thanx for posting this article :)
Left by manu on Feb 29, 2012 4:16 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Mate this code worked perfectly for me, you've solved an evenings work, I'm absolutely chuffed to have the damn thing working, now I can finish my assignment!

Thank you!!!
Left by Steve on Apr 16, 2012 4:46 AM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Nice...Thanks a lot
Left by Badre on May 02, 2012 9:45 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Hi All,
I think below code will help you in simplest way.

<head runat="server">
<title>Accessing GridView Hidden Column value </title>
<style type="text/css">
.hiddencol
{
display: none;
}
</style>

<asp:BoundField HeaderText="Email ID" DataField="EmailId" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" >
</asp:BoundField>

ArrayList EmailList = new ArrayList();
foreach (GridViewRow itemrow in gvEmployeeDetails.Rows)
{
EmailList.Add(itemrow.Cells[YourIndex].Text);
}
Left by Mubashir Ahmed on May 21, 2012 2:53 PM

# re: FAQ: How to Get Hidden Column values in GridView
Requesting Gravatar...
Thank you very much!
bts
Left by bts on Oct 05, 2012 6:54 PM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net