从函数中的sqldatereader访问数据

时间:2011-10-26 13:56:47

标签: asp.net

我想根据用户名向用户输出一些数据。此数据保存在链接到aspnet_Users表的表中。我正在尝试将sqldatareader编写为函数的一部分,因此当从多个页面调用代码时,我不必重写代码。我知道这可能非常简单但我似乎无法从函数外部访问数据。我到目前为止的功能如下:

Public Shared Function AgencyDetails() As SqlDataReader
    Dim details As String = "SELECT * FROM tbl_Relationships WHERE ContactSub = @Username"
    Dim connString As String = ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString

    Using dbConnection As New SqlConnection(connString)
        dbConnection.Open()
        Dim cmdAgency As New SqlCommand(details, dbConnection)
        cmdAgency.Parameters.AddWithValue("@Username", membership.getuser)
        Return cmdAgency.ExecuteReader()


    End Using
End Function

如何调用此功能并访问我页面上的信息?像下面这样的东西?

lblAgencyDetails.text = AgencyDetails(0)

由于

2 个答案:

答案 0 :(得分:0)

你现在拥有它的方式,它将无法工作,因为你在using语句中包含了连接,当你返回Reader时,连接将被关闭并处理掉读者将无法阅读任何内容。

您应该在该函数中执行的操作是在DataTable中加载信息并返回数据表。

示例:

Public Shared Function AgencyDetails() As DataTable
    Dim details As String = "SELECT * FROM tbl_Relationships WHERE ContactSub = @Username"
    Dim connString As String = ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString

    Using dbConnection As New SqlConnection(connString)
        dbConnection.Open()
        Dim cmdAgency As New SqlCommand(details, dbConnection)
        cmdAgency.Parameters.AddWithValue("@Username", membership.getuser)
        Dim dt as new DataTable()
        dt.Load(cmdAgency.ExecuteReader())
        return dt

    End Using
End Function

您可以通过执行以下操作来访问数据表中的行:

For Each row as DataRow in dt.Rows
   Console.WriteLine(row("ColumnName"))
Next

答案 1 :(得分:0)

为了能够从DataReader对象中检索数据,您应该调用Read()方法:

 While reader.Read()
        Console.WriteLine(String.Format("{0}, {1}", _
            reader(0), reader(1)))
    End While

此方法将SqlDataReader移动到下一条记录。