如何在Datagrid视图中添加到期日期

时间:2019-04-04 13:25:29

标签: vb.net

我有此代码:

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

1 个答案:

答案 0 :(得分:1)

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块可确保即使发生错误也可以关闭和处置数据库对象。