Reputation: 4292
I am trying to get the value from a GridView and save it as a Session variable.
I know the column name and there is only ever one value in the GridView. What is the best way to select it and save as the Session variable?
The column name is CustomerID and the value is always a int.
Upvotes: 1
Views: 1256
Reputation: 1755
You can set a DataKey
for GridView as CustomerID and select by:
int ID = Convert.ToInt32(GridView1.DataKeys[indx].Value);
indx
is Row Index in GridView..
Upvotes: 1
Reputation: 573
This is not a proper way to do this, you better hardcode the cellindex but anyways a little longer version of Damith's answer
if (GridView1.Rows.Count > 0)
{
int indexofcolumn = 0;
foreach (DataControlField column in GridView1.Columns)
{
if (column.HeaderText == "CustomerID") break;
indexofcolumn++;
}
Session["CustomerID"] = GridView1.Rows[0].Cells[indexofcolumn].Text;
}
Upvotes: 1
Reputation: 63105
if there is one column and one row in the GridView you can try below.
Session["MySessionValue"]= GridView1.Rows[0].Cells[0].Text;
but exception can be thrown when you access by index if there is no records in the GridView. So better to check GridView1.Rows.Count
First and get the value
Upvotes: 2