首页 > 解决方案 > 如何在数据网格视图中添加到期日期

问题描述

我有这个代码:

Dim readers As MySqlDataReader
Dim command As New MySqlCommand
Try
    con.Open()
    Dim query As String
    query = "Select product_code,drug_name,quantity,expiration_date from medicine where expiration_date<=@exp"
    command = New MySqlCommand(query, con)
    command.Parameters.Add("@exp", MySqlDbType.DateTime).Value = DateTime.Now
    readers = command.ExecuteReader
    Dim count As Integer
    count = 0
    While readers.Read
        count = count + 1
    End While
    con.Close()
    If count = 0 Then
        MsgBox("no expiration")
    Else
        DataGridView1.Rows.Add(readers)
    End If
Catch ex As Exception
    MessageBox.Show(ex.Message)
End Try

标签: vb.net

解决方案


Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim dt As New DataTable
    Using con As New MySqlConnection("your connection string")
        Using command As New MySqlCommand("Select product_code,drug_name,quantity,expiration_date from medicine where expiration_date<=@exp", con)
            command.Parameters.Add("@exp", MySqlDbType.DateTime).Value = DateTime.Now
            con.Open()
            dt.Load(command.ExecuteReader)
        End Using
    End Using
    If dt.Rows.Count < 1 Then
        MsgBox("no expiration")
    Else
        DataGridView1.DataSource = dt
    End If
End Sub

如果您的目标是显示查询的返回值,这应该可以工作。Using...End Using即使出现错误,这些块也可确保您的数据库对象已关闭和处置。


推荐阅读