如何在gridview中获取所选行的值 [英] How to get the value of a selected row in gridview
问题描述
大家好,
我有一个gridview,我放置了一些绑定字段,并在网格的最后一列添加了一个图像按钮作为模板字段。< br $>
我想要的是当我点击图片按钮时,我的页面应该重定向到一个包含列值的新页面,比如我点击的行的ID。
我可以使用会话或查询字符串进行重定向,但如何获取行值?
我尝试了很多方面,但我得到一个空引用错误。
我无法使用图像按钮获取所选行。
如何编码图像按钮以选择行并获取其值?
请帮助我。
提前感谢...
Hi all,
I have a gridview there I placed some bound field and also added an image button in the last column of the grid as template field.
What I want is when I click on the image button my page should redirect to a new page with one of column values, say the id of the row where I clicked.
I can use session or query string for redirecting but how to get the row values?
I tried in many ways but I get a null reference error.
I''m unable to get the selected row using an image button.
How can I code the image button to select a row and get its values?
Please help me.
Thanks in advance...
推荐答案
转到选择更改事件并编写以下代码:
选择更改事件
int index = gridvview.selectedindex;
session [id] =(gridview.ro ws [index] .cells [0] .text).tostring();
通过这种方式,您可以从所选行中获取所有单元格的值
go to selection changing event and write the code below:
Selection changeing Event
int index=gridvview.selectedindex;
session["id"]=(gridview.rows[index].cells[0].text).tostring();
in this way you get all your cell''s values from selected row
尝试详细了解这个 MSDN文章 [ ^ ]。
基本上,您需要获取按钮所在行的索引。然后,您可以使用该索引获取特定行:
GridViewRow row = ContactsGridView.Rows [index];
然后,您可以获得所需列的内容,例如:
String s = row.Cells [2] .Text;
变量s将具有gridview所选行(点击按钮的位置)的第三个单元格的值。
我分享的链接有一个例子。
Try exploring more on this MSDN Article[^].
Basically, you need to get the index of the row where the button is located. You can then get the specific row using that index:
GridViewRow row = ContactsGridView.Rows[index];
You can then get the content of the column that you want, for example:
String s = row.Cells[2].Text;
The variable s will have the value of third cell of the selected row (where your button was clicked) of you gridview.
There is an example on the link I shared.
一种方法是为该图像按钮添加Click事件并获取行如下,
One way is to add Click event for that image button and get the row as,
GridviewRow gvRow = (sender as ImageButton).NamingContainer as GridviewRow;
然后访问您要传递的DataKey或ID。
PS:代码未经过测试。
或者你可以使用RowCommand。
and then access the DataKey or ID which you want to pass.
PS: Code is not tested.
Alternatively you can use RowCommand.
这篇关于如何在gridview中获取所选行的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!