循环遍历gridview并获取数据键值

时间:2011-11-25 03:45:23

标签: asp.net vb.net

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

  

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

2 个答案:

答案 0 :(得分:10)

您可以遍历.Rows集合,然后找到行的DataKey值。

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

答案 1 :(得分:6)

您必须使用Value属性。

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