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.
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
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..
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.