Search code examples
vb.netlistviewpopulate

How to populate a listview between two dates vb.net


I am writing a code that filters the listview data between two selected dates. The code is not working, i am not finding a way to make it work in a listview, although it works on a datagrid.

listavalor.Items.Clear()
Dim dt As New DataTable
Dim ds As New DataSet
ds.Tables.Add(dt)
Dim coiso As New MySqlCommand("SELECT * FROM custospessoais WHERE CUS_DATA BETWEEN '" &
     Format(datapicker1.Value, "dd-MM-yyyy") & "' AND '" &
     Format(datapicker2.Value, "dd-MM-yyyy") & "' CUS_ID;")
Dim da As New MySqlDataAdapter(coiso)
da.Fill(dt)
Dim coluna As DataRow
For Each coluna In dt.Rows
    listavalor.Items.Add(coluna.Item(0))
    listavalor.Items(listavalor.Items.Count - 1).SubItems.Add(coluna.Item(1))
    listavalor.Items(listavalor.Items.Count - 1).SubItems.Add(coluna.Item(2))
    listavalor.Items(listavalor.Items.Count - 1).SubItems.Add(coluna.Item(3))
Next

Solution

    1. Use a date or datetime type in the DB, not a text type, to store dates.
    2. Use command parameters. This makes the code immune to formatting problems and SQL injection.
    3. If you don't follow the advice from 1. and 2., at least use the inverse date format yyyy-MM-dd.
      1. If the date is stored as text it still sorts and compares right.
      2. You don't have a problem US-style dates MM-dd-yyyy.

    See also: MySQL Data Types