在单个 MessageBox 中显示多行 DataReader

Showing multiple rows of DataReader in single MessageBox

我想在 MessageBox 中显示来自 Access 数据库的数据,但我只找到了一种显示单行的方法。我想在所有行的列中显示数据。这是我使用的代码:

Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

       Dim dr As OleDbDataReader
       Try
           con.Open()
           str = "SELECT CUSTOMER.CustName,RECEIPT.ReceiptDate, CUSTOMER_ORDER.DateExpired  FROM ((CUSTOMER INNER JOIN RECEIPT ON CUSTOMER.CustID = RECEIPT.CustID) INNER JOIN CUSTOMER_ORDER ON CUSTOMER_ORDER.ReceiptID = RECEIPT.ReceiptID) INNER JOIN PRODUCT ON PRODUCT.ProdID = CUSTOMER_ORDER.ProdID WHERE YEAR (DateExpired) = 2015"
           Using command As New OleDbCommand(str, con)
               dr = command.ExecuteReader

               If dr.HasRows Then
                   dr.Read()
                   sname = dr.Item("CustName")
                   sdate = dr.Item("ReceiptDate")
                   expdate = dr.Item("DateExpired")
                   dr.Close()
               End If

           End Using

           con.Close()
       Catch ex As Exception
           MsgBox(ex.Message)
       End Try

       'con.Open()
       MessageBox.Show("Customer" & vbTab & vbTab & "DateReceipt" & vbTab & "Expired" & vbNewLine & "**********************************************************" & vbNewLine & sname & vbTab & sdate & vbTab & vbTab & expdate, "Reminder!", MessageBoxButtons.OK)
       con.Close()

   End Sub

如果我没理解错的话,你有一个 DbReader 并且你想显示一个包含多行字符串的消息框。

Dim msg=""
Try
    con.Open()
    str = "SELECT CUSTOMER.CustName, RECEIPT.ReceiptDate, CUSTOMER_ORDER.DateExpired " & _
          "FROM ((CUSTOMER INNER JOIN RECEIPT ON CUSTOMER.CustID = RECEIPT.CustID) INNER JOIN CUSTOMER_ORDER ON CUSTOMER_ORDER.ReceiptID = RECEIPT.ReceiptID) INNER JOIN PRODUCT ON PRODUCT.ProdID = CUSTOMER_ORDER.ProdID " & _
          "WHERE YEAR (DateExpired) = 2015"
    Using command = con.CreateCommand(str), dr = command.ExecuteReader
        msg = String.Join(vbCrLf, dr.Cast(Of DbDataRecord).Select(Function(row)
            Return $"{row("CustName")} #{row("ReceiptDate")}#"
        End Function))
    End Using
    con.Close()
Catch ex As Exception
    MsgBox(ex.Message)
End Try
MsgBox(msg)

注意 在我的项目中,我通常会添加一个 Joined 扩展方法,它是 String.Join:

的包装器
<Extension> Function Joined(Of T)(source As IEnumerable(Of T), Optional delimiter As String = ",", Optional selector As Func(Of T, String) = Nothing) As String
    If source Is Nothing Then Return ""
    If selector Is Nothing Then Return String.Join(delimiter, source)
    Return String.Join(delimiter, source.Select(selector))
End Function

然后创建消息的代码变为:

msg = dr.Cast(Of DbDataRecord).Joined(vbCrLf, Function(row) $"{row("CustName")} #{row("ReceiptDate")}#")