Wednesday, February 24, 2010

Get Value From Invisible Column in Gridview

Sometimes we want to store any ID in the GridView and not to show to the user. Ok, but problem arises when we want to get the invisible value from the selected row.

Basically, Microsoft have decided that hidden columns in DataGrids were almost always used to store primary keys of records, and that maintaining them in ViewState represented a security risk. Therefore, in the GridView object introduced in v2, hidden columns have been removed from ViewState by default, which is why the columns themselves are still there (otherwise you
couldn't reference them in the CodeFile), but their values are blank.

Fortunately, there is an easy workaround. Simply set the column(s) to Visible immediately before invoking the GridView's DataBind() method, and then hide them again immediately after. E.g.
MyGridView.DataSource =
MyGridView.Columns[x].Visible = true;
MyGridView.DataBind();
MyGridView.Columns[x].Visible = false;

Now you can get the values of all columns after the GridView having selected:

GridViewRow row = gvCodeDetails.SelectedRow;

for (int count = 0; count < row.Cells.Count; count++)
{
Response.Write("Count: " + count + " " + row.Cells[count].Text + "<br />");
}
This code is for getting and displaying all columns of any selected GridView row; you will use that one you need.

It seems good but sometimes it causes problems. I do not find any value of the hidden field, found blank instead. However, here is a rather better way I find to be more effective.

Keep the columns you want to store hidden in the DataKeyNames facility.

if you wan't to hide two columns then you can set multiple columns in the DataKeyNames like:
Write column names separated by comma at the gridview properties DataKeyNames field.

Alternatively you can write manually on the source view

DataKeyNames="Column1, Column2"

then you can access it this way:

string key1 = GridView1.DataKeys[rowIndex].Values[0].ToString(); //first key
string key2 = GridView1.DataKeys[rowIndex].Values[1].ToString(); //second key

In this way you can retrieve the values from the gridview.

No comments: