[英]Get value from GridView
I am trying to get the value from a GridView and save it as a Session variable. 我试图从GridView获取值并将其保存为Session变量。
I know the column name and there is only ever one value in the GridView. 我知道列名,GridView中只有一个值。 What is the best way to select it and save as the Session variable?
选择它并保存为Session变量的最佳方法是什么?
The column name is CustomerID and the value is always a int. 列名称为CustomerID,值始终为int。
if there is one column and one row in the GridView you can try below. 如果GridView中有一列和一行,您可以在下面尝试。
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. 但是如果GridView中没有记录,则可以通过索引访问异常。 So better to check
GridView1.Rows.Count
First and get the value 最好先检查
GridView1.Rows.Count
并获取值
You can set a DataKey
for GridView as CustomerID and select by: 您可以将GridView的
DataKey
设置为CustomerID并选择:
int ID = Convert.ToInt32(GridView1.DataKeys[indx].Value);
indx
is Row Index in GridView.. indx
是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 这不是一个正确的方法,你最好硬编码cellindex,但无论如何更长的版本Damith的答案
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.