Thursday 11 June 2015

Get value of BoundField column set to Visible=False in GridView

 When you set Visible property to False for a BoundField column then it is not possible to get value of such column and hence you need to make use of DataKeyNames (DataKeys) property of ASP.Net GridView.

What are DataKeyNames and DataKeys?
      DataKeyNames is the property of GridView which allows us to set the names of the Column Fields that we want to use in code but do not want to display it. Example Primary Keys, ID fields, etc.
The values Column Fields which are set in DataKeyNames are available in code in DataKeys object which saves it in an Array called as DataKeyArray.

 Using DataKeyNames and DataKeys in GridView
   Using DataKeyNames and DataKeys is fairly simple, you just need to set the name of the Column in DataKeyNames property as shown below. Here CustomerId is the name of the Column.
DataKeyNames="CustomerId"

And then in code access it using the RowIndex of the GridView Row to get the value of the Column for that particular Row.
int id = Convert.ToInt32(GridView1.DataKeys[rowIndex].Values[0]);







 Getting the DataKeys value for a particular GridView Row
Inside the Button click event handler, first the GridView Row is determined using the NamingContainer property and then finally the Row Index is determined.
Using the Row Index, the DataKeys array is accessed and the value of the Column is fetched.
C#
protected void GridView_Button_Click(object sender, EventArgs e)
{
    //Determine the RowIndex of the Row whose Button was clicked.
    int rowIndex = ((sender as Button).NamingContainer as GridViewRow).RowIndex;

    //Get the value of column from the DataKeys using the RowIndex.
    int id = Convert.ToInt32(GridView1.DataKeys[rowIndex].Values[0]);
}

VB.Net
Protected Sub GridView_Button_Click(sender As Object, e As EventArgs)
    'Determine the RowIndex of the Row whose Button was clicked.
    Dim rowIndex As Integer = TryCast(TryCast(sender, Button).NamingContainer, GridViewRow).RowIndex

    'Get the value of column from the DataKeys using the RowIndex.
    Dim id As Integer = Convert.ToInt32(GridView1.DataKeys(rowIndex).Values(0))
End Sub

No comments:

Post a Comment