VB.net Gridview DataKeys用于信息显示

时间:2014-04-13 12:45:47

标签: sql vb.net gridview

我正在尝试从gridview中选择一行,然后显示与该行中的数据相关的更多信息。为了做到这一点,我设置了一个DataKey,在这种情况下是ID。然后,我想访问我的数据库并选择ID等于所选行的DataKey的ID的所有记录。遗憾的是我遇到了一些麻烦,因为我不知道如何正确访问我所选行的DataKey。以下是我的代码。我试图获取datakey的值并将其设置为int,然后在我的SELECT语句中使用返回值。

     Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
    Dim RegDataConn1 As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; data source=" & Server.MapPath("App_Data/1202389.mdb"))
    Dim i As Integer = GridView1.SelectedIndex
    Dim hotelid As Integer = GridView1.DataKeys(i).Value




    Dim cmd1 As OleDbCommand = New OleDbCommand("SELECT * FROM Ratings WHERE Hotel.Hotel_ID=" & hotelid.ToString(), RegDataConn1)
    RegDataConn1.Open()
    Dim myDA1 As OleDbDataAdapter = New OleDbDataAdapter(cmd1)
    Dim myDataSet1 As DataSet = New DataSet
    myDA1.Fill(myDataSet1, "Table1")
    GVDetailView.DataSource = myDataSet1.Tables("Table1").DefaultView
    GVDetailView.DataBind()
    RegDataConn1.Close()

End Sub

http://postimg.org/image/yp3ukwsdv/这是我的错误图片

2 个答案:

答案 0 :(得分:1)

您的查询字符串不是动态的

" SELECT Service_Rating,Price_Rating,Clean_Rating,Location_Rating,Overall_Rating,Text_Review FROM Ratings WHERE Hotel.Hotel_ID = hotelid"

应该是

" SELECT Service_Rating,Price_Rating,Clean_Rating,Location_Rating,Overall_Rating,Text_Review FROM Ratings WHERE Hotel.Hotel_ID =" &安培; hotelid.ToString

虽然这可能会解决您的问题,但我建议您使用存储过程,而不是动态SQL。它更快,更安全。

答案 1 :(得分:1)

获取datakey的值应为:

Dim hotelid As String = GridView1.DataKeys(i).Value.ToString()

如果真的是,则将类型转换为整数。

你错过的是告诉GridView它的DataKeyNames

为此,请将gridview的标记更改为:

<asp:GridView ID="GridView1" runat="server" DataKeyNames="hotelid">
</asp:GridView>