2011-11-25 73 views
4

我想通过我的gridview行并检索每行的数据键值然后执行一些代码来运行sql查询。我如何获得变量中每一行的数据键值?现在我收到一条错误消息:通过gridview循环并获取数据键值

类型system.web.ui.webcontrols.datakey的值无法转换为整数。

这里是我的代码:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
    For Each row As GridViewRow In GridView1.Rows 
     Dim therowindex As Integer = row.RowIndex 

     Dim theid As Integer = GridView1.DataKeys([therowindex]) 

     'execute some more code running queries using the data key value. 
    Next 
End Sub 

回答

6

你必须使用Value财产。

Dim theid As Integer = Integer.Parse(GridView1.DataKeys(therowindex).Value.ToString()) 
10

您可以通过.Rows访问集合,然后找到该行的DataKey值。

foreach(GridViewRow row in GridView1.Rows) 
{ 
    string theDataKey = GridView1.DataKeys[row.RowIndex].Value.ToString(); 
    // Do something with your index/key value 
}