在单个MessageBox中显示多行DataReader

时间:2015-08-13 07:29:13

标签: vb.net ado.net

我想在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

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您有一个MainActivityMapper extends ActivityMapper,并且您希望显示一个包含多行字符串的消息框。

DbReader

NB在我的项目中,我通常会添加一个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