• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2064
  • Last Modified:

Listview - dynamic expiry date counter on Timer vb.net

Hi Experts,

Apologies if I babble on a bit.

I'm trying to create a small winform app with:
1 Listview (4 columns)
1 Textbox
Label1 = current date
DateTimePicker1
3 Buttons (ADD, LOAD, SAVE)

Label1.Text = DateTime.Now.ToShortDateString()

ACTIONS:

1. User Type's a Grocery name into Textbox1, Label1 will capture todays date and DateTimePicker1 will capture expiry date (future only).
2. click ADD button.

Dim pItem As ListViewItem
        pItem = New ListViewItem
        pItem.UseItemStyleForSubItems = False 'Use this line to style subitem
        pItem.Text = TextBox1.Text
        pItem.SubItems.Add(Label1.Text)
        pItem.SubItems.Add(DateTimePicker2.Text)
        ListView1.Items.Add(pItem)
        ListView1.Refresh()

Open in new window


I'd like to add a dynamic counter in column 3 which will show date of expiry - DD, MM, YYY, HH, MM, SS

If I click Save, this will save (not append) to a text file on C:\somefile.txt

If click LOAD, then load the data: e.g. "Apples;date-stamp1;expiry date-stamp2;counter"

All column4 data will be replaced by dynamic counter on Timer until SAVE is clicked...  this will replace current text data... hope this makes sense.

Formula: Column1; start date (today if necessary); expiry date; counter = WORKS OUT DIFFERENCE BETWEEN start date & expiry date and display in Column4.

So if ("LOAD") button is clicked and there are example = 4 Items;date stamp;expiry stamp in the txt file... then only expiry stamp will change on save (this bit I don't fully understand)

I hope this makes sense... I'm confused.

Thanks,
Rob
0
RobertoFreemano
Asked:
RobertoFreemano
  • 17
  • 15
  • 5
2 Solutions
 
Jesus RodriguezIT ManagerCommented:
Let's retake your previous code.
On This part
Dim pItem As ListViewItem
        pItem = New ListViewItem
        pItem.UseItemStyleForSubItems = False 'Use this line to style subitem
        pItem.Text = TextBox1.Text
        pItem.SubItems.Add(Label1.Text)
        pItem.SubItems.Add(DateTimePicker2.Text) & " " & Now.TimeOfDay.ToString()
        ListView1.Items.Add(pItem)
        ListView1.Refresh()


Add A timer an set the Timer1.Tick=1000

The on the Event OnTimer1_Tick do something like this

If Me.ListViewItems1.Count>0 then 'If the listview has items
  For Each Item as ListViewItem in ListviewItem
     Dim TimeItem as string=item.SubListitem(2).value 'Or Text, don't rememmber
     Dim NewTime as string=DateAdd(DateInterval.Second, -1, CDate(TimeItem)).ToString
     Item.SubItem(2)=NewTime
  Next
End If
Me.listview1.refresh()

Is more or less something like this.. Also you has to check for the time result=current date to mark as delete
0
 
Jesus RodriguezIT ManagerCommented:
Like This more or less

If Me.ListViewItems1.Count>0 then 'If the listview has items
  For Each Item as ListViewItem in ListviewItem
   If item.subListItem(2).value<>"To Delete" then
      Dim TimeItem as string=item.SubListitem(2).value 'Or Text, don't rememmber
      Dim NewTime as string=DateAdd(DateInterval.Second, -1, CDate(TimeItem)).ToString
      if Cdate(NewTime)=Now() then
            Item.SubItem(2)="To Delete"
      else
           Item.SubItem(2)=NewTime
      End If
    End If
  Next
End If
Me.listview1.refresh()

Also suggest to you that do that every 10 seconds more or less or every a minute to let the other process run smothly (adding a new grocery or something else)
0
 
RobertoFreemanoAuthor Commented:
Hi k-designers,

I've made a right mess of this... let me start again and lay it down bit by bit
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
RobertoFreemanoAuthor Commented:
this is the form - how it looks
Label2 = todays.date
Label1 = timer
0
 
RobertoFreemanoAuthor Commented:
Here's what I started with, with one of your bits added ;)

Imports System.IO

Dim pItem As ListViewItem

Public Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.DateTimePicker1.MinDate = Today
        CheckListView()

        Label2.Text = DateTime.Now.ToLongDateString()
       ' load into Listview1
        Try
            Dim values() As String
            Dim fileName As String = "c:\tim\grocies.txt"
            ListView1.Items.Clear()
            Dim sr As New System.IO.StreamReader(fileName)
            Dim line As String = sr.ReadLine
            While Not (line Is Nothing)
                If line.ToUpper.IndexOf(TextBox9999.Text.ToUpper) <> -1 Then
                    values = line.Split(";")
                    ListView1.Items.Add(New ListViewItem(values))
                End If
                line = sr.ReadLine
            End While
            sr.Close()
        Catch ex As Exception
            MsgBox("New session will start")
        End Try
    End Sub

'For the Button to add item
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        If ComboBox1.Text = "" Then
        Else
            Dim pItem As ListViewItem
            pItem = New ListViewItem
            pItem.UseItemStyleForSubItems = False 'Use this line to style subitem
            pItem.Text = ComboBox1.Text
            pItem.SubItems.Add(Label2.Text)
            pItem.SubItems.Add(DateTimePicker1.Text)
            pItem.SubItems.Add(Label1.Text)
            ListView1.Items.Add(pItem)
            ListView1.Refresh()
        End If
        Listview1.refresh()
    End Sub

 Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
        
        Dim startdate As DateTime = DateTime.Parse(Date.Now)
        Dim enddate As Date = Date.Parse(DateTimePicker1.Text)
        Dim ts As TimeSpan = enddate.Subtract(startdate)
        Label1.Text = CStr(ts.Days) & " Days, " & CStr(ts.Hours) & " Hours, " & CStr(ts.Minutes) & " minutes, " & CStr(ts.Seconds) & " sec"
    End Sub

'Create This Sub
    Public Sub CheckListView()
        For Each item As ListViewItem In Me.ListView1.Items
            If CDate(item.SubItems(0).Text) < Today Then 'Get the date of the item
                Dim NewIt As New ListViewItem
                NewIt.UseItemStyleForSubItems = False 'Use this line to style subitem
                NewIt.Text = item.Text
                ListView1.Items.RemoveAt(item.Index)
                NewIt.SubItems.Add(NewIt.Text)
                NewIt.SubItems.Add("To Delete")
            End If
        Next
        ListView1.Refresh()
    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        Try
            Dim myFile As String = "c:\tim\grocies.txt"
            Dim myWriter As New IO.StreamWriter(myFile)
            For Each myItem As ListViewItem In ListView1.Items
                myWriter.WriteLine(myItem.Text & ";" & myItem.SubItems(1).Text & ";" & myItem.SubItems(2).Text & ";" & myItem.SubItems(3).Text)
            Next
            myWriter.Close()
        Catch ex As Exception
            MsgBox("OOPS")
        End Try
        
    End Sub

Open in new window

0
 
RobertoFreemanoAuthor Commented:
The code above works with no dynamic bits in column4
0
 
RobertoFreemanoAuthor Commented:
I've added your snippet of code: by: k-designersPosted on 2012-08-28 at 16:22:00ID: 38341881

but get errors :(

on Timer1
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
First line should probably be:

    If Me.ListView1.Items.Count > 0 Then

Second line with error should probably be:

        For Each Item As ListViewItem In ListView1.Items
0
 
RobertoFreemanoAuthor Commented:
Hi Mike,

Thanks for your input.

looking the at form (above)... is ther no sollution to just say:

1. load file into Listvoew
2. calculate all entries in column2 & 3... then column4 (EXPIRES IN) calc date diff =  START DATE and END DATE?
0
 
Jesus RodriguezIT ManagerCommented:
Sorry, I was out for a while.. As Idle said, is Listview1.items.count
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
The values in a ListView are STATIC (not changing).  This will work the first time the form is opened.  Those "expires in" values will be invalid after the form has been open for awhile though.

If you want actual real-time countdowns for each one then you have to re-compute those values often enough to make them appear to be continuously counting down...
0
 
Jesus RodriguezIT ManagerCommented:
On this Part of the code you must do this


Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
       
If Me.ListView1.Items.Count>0 then 'If the listview has items
  For Each Item as ListViewItem in Listview.Items
     Dim TimeItem as string=item.SubListitem(2).value 'Or Text, don't rememmber
     Dim NewTime as string=DateAdd(DateInterval.Second, -1, CDate(TimeItem)).ToString
     Item.SubItem(2)=NewTime
  Next
End If
 Me.listview1.refresh()
 CheckListView()
End Sub
0
 
RobertoFreemanoAuthor Commented:
perhaps i'm trying to be too ambitious - lol

I'm just trying to timestamp on a text file, but the value of column2&3 = result in 4

My head hurts - lol
0
 
Jesus RodriguezIT ManagerCommented:
Let My Try to reproduce the whole code on my end and Will get back to you as soon as I can, give 15 minutes to see
0
 
RobertoFreemanoAuthor Commented:
Thanks k-designers & thanks Mike = you guys rock!
0
 
RobertoFreemanoAuthor Commented:
was thinking of something like...
Dim lvi As ListViewItem
        For Each lvi In ListView1.Items
            MessageBox.Show(lvi.Text)
            pItem.SubItems(3).Text = "test"
            ListView1.Items.Add(pItem)
            ListView1.Refresh()
        Next

Open in new window

A Do Loop to scan through listview columns.... obviously this doesn't work... just thinking out loud ;)
0
 
Jesus RodriguezIT ManagerCommented:
I got your whole code here

    Public Sub CheckListView()
        For Each item As ListViewItem In Me.ListView1.Items
            If CDate(item.SubItems(2).Text) < Now Then 'Get the date of the item
                Dim NewIt As New ListViewItem
                NewIt.UseItemStyleForSubItems = False 'Use this line to style subitem
                NewIt.Text = item.Text
                NewIt.SubItems(0).Text = item.SubItems(0).Text
                NewIt.SubItems(1).Text = item.SubItems(1).Text
                NewIt.SubItems(2).Text = "To Delete"
                ListView1.Items.RemoveAt(item.Index)
            End If
        Next

        ListView1.Refresh()
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        If ComboBox1.Text = "" Then
        Else
            Timer1.Stop()
            Dim pItem As ListViewItem
            pItem = New ListViewItem
            pItem.UseItemStyleForSubItems = False 'Use this line to style subitem
            pItem.Text = ComboBox1.Text
            pItem.SubItems.Add(Now.ToString)
            pItem.SubItems.Add(DateTimePicker1.Text & " " & Now.TimeOfDay.ToString())
            pItem.SubItems.Add(DateDiff(DateInterval.Second, Now, CDate(DateTimePicker1.Text & " " & Now.TimeOfDay.ToString())).ToString)
            ListView1.Items.Add(pItem)
            ListView1.Refresh()
            Timer1.Start()
        End If
     
    End Sub

    Private Sub EXp_Exchangevb_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        Try
            Dim myFile As String = "c:\tim\grocies.txt"
            Dim myWriter As New IO.StreamWriter(myFile)
            For Each myItem As ListViewItem In ListView1.Items
                myWriter.WriteLine(myItem.Text & ";" & myItem.SubItems(1).Text & ";" & myItem.SubItems(2).Text & ";" & myItem.SubItems(3).Text)
            Next
            myWriter.Close()
        Catch ex As Exception
            MsgBox("OOPS")
        End Try

    End Sub

    Private Sub EXp_Exchangevb_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Me.DateTimePicker1.MinDate = Today
        Try
            Dim values() As String
            Dim fileName As String = "c:\tim\grocies.txt"
            ListView1.Items.Clear()

            Dim sr As New System.IO.StreamReader(fileName)
            Dim line As String = sr.ReadLine()
            Do Until line Is Nothing
                values = line.Split(";")
                Dim NLIte As New ListViewItem
                NLIte.Text = values(0)
                For I As Integer = 1 To values.Length - 1
                    NLIte.SubItems.Add(values(I))
                Next
                ListView1.Items.Add(NLIte)
                line = sr.ReadLine
            Loop
            sr.Close()
        Catch ex As Exception
            MsgBox("New session will start")
        End Try
        CheckListView()
        Timer1.Interval = 10000
        Timer1.Start()
    End Sub


    Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
        If Me.ListView1.Items.Count > 0 Then 'If the listview has items
            For Each Item As ListViewItem In ListView1.Items
                Dim TimeItem As String = Item.SubItems(2).Text  'Or Text, don't rememmber
                Dim DIfference As String = DateDiff(DateInterval.Second, Now, CDate(TimeItem)).ToString
                Item.SubItems(3).Text = DIfference
            Next
        End If
        Me.ListView1.Refresh()
        CheckListView()
    End Sub
0
 
Jesus RodriguezIT ManagerCommented:
Needs to make a correction to some code.. Hold for a minute
0
 
Jesus RodriguezIT ManagerCommented:
Here is the Changes

 Public Sub CheckListView()
        For Each item As ListViewItem In Me.ListView1.Items
            If CDate(item.SubItems(2).Text) < Now Then 'Get the date of the item
                Dim NewIt As New ListViewItem
                NewIt.UseItemStyleForSubItems = False 'Use this line to style subitem
                NewIt.Text = item.Text
                NewIt.SubItems.Add(item.SubItems(0).Text)
                NewIt.SubItems.Add(item.SubItems(1).Text)
                NewIt.SubItems.Add("To Delete")
                Me.ListView1.Items.Add(NewIt)
                ListView1.Items.RemoveAt(item.Index)
            End If
        Next

        ListView1.Refresh()
    End Sub



 Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        If ComboBox1.Text = "" Then
        Else
            Dim pItem As New ListViewItem
            Timer1.Stop()
            pItem.UseItemStyleForSubItems = False 'Use this line to style subitem
            pItem.Text = ComboBox1.Text
            pItem.SubItems.Add(Now.ToString)
            pItem.SubItems.Add(Strings.Format(DateTimePicker1.Value, "MM/dd/yyyy") & " " & Now.TimeOfDay.ToString())
            pItem.SubItems.Add(DateDiff(DateInterval.Second, Now, CDate(DateTimePicker1.Text & " " & Now.TimeOfDay.ToString())).ToString)
            ListView1.Items.Add(pItem)
            ListView1.Refresh()
            Timer1.Start()
        End If

    End Sub

 The only that you need now is a function to convert the second in Month/Days/Hours/Seconds to display it correctly

Also you don't need the Save button because the form will do it on the close event or if you want you can add tis code to the save button

Try
            Dim myFile As String = "c:\tim\grocies.txt"
            Dim myWriter As New IO.StreamWriter(myFile)
            For Each myItem As ListViewItem In ListView1.Items
                myWriter.WriteLine(myItem.Text & ";" & myItem.SubItems(1).Text & ";" & myItem.SubItems(2).Text & ";" & myItem.SubItems(3).Text)
            Next
            myWriter.Close()
        Catch ex As Exception
            MsgBox("OOPS")
        End Try
0
 
Jesus RodriguezIT ManagerCommented:
I attach the Form and the code for better understand on you end
EXp-Exchangevb.vb
EXp-Exchangevb.resx
EXp-Exchangevb.Designer.vb
0
 
RobertoFreemanoAuthor Commented:
wow, this is amazing...

I added an item and after a minute or so, it crashed..

System.InvalidCastException was unhandled
  Message=Conversion from string "TOOTHBRUSH" to type 'Date' is not valid.
  Source=Microsoft.VisualBasic
  StackTrace:
       at Microsoft.VisualBasic.CompilerServices.Conversions.ToDate(String Value)
       at Foody.Form1.Timer1_Tick(Object sender, EventArgs e) in C:\Users\bob\documents\visual studio 2010\Projects\Foody\Foody\Form1.vb:line 87
       at System.Windows.Forms.Timer.OnTick(EventArgs e)
       at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at Foody.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
0
 
Jesus RodriguezIT ManagerCommented:
Is On the way that It save, let me check again..
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Here's a different approach to consider...

Just add a DataGridView and a Timer to a blank form, and watch what happens:
Public Class Form1

    Private data As New DataTable

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        data.Columns.Add("Item", GetType(String))
        data.Columns.Add("Purchased", GetType(DateTime))
        data.Columns.Add("Expires", GetType(DateTime))
        data.Columns.Add("Time Left", GetType(String))

        data.Rows.Add(New Object() {"Milk", DateTime.Now, DateTime.Now.AddDays(7), ""})
        data.Rows.Add(New Object() {"Eggs", DateTime.Now, DateTime.Now.AddDays(14), ""})
        data.Rows.Add(New Object() {"Bananas", DateTime.Now, DateTime.Now.AddDays(4), ""})
        data.Rows.Add(New Object() {"Hot Cheeseburger", DateTime.Now, DateTime.Now.AddSeconds(15), ""})

        DataGridView1.DataSource = data
        DataGridView1.Dock = DockStyle.Fill
        DataGridView1.AllowUserToAddRows = False
        DataGridView1.AllowUserToDeleteRows = False
        DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
        DataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically

        Timer1.Interval = 1000
        Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
        Dim TS As TimeSpan
        Dim purchased, expires As DateTime
        For Each row As DataRow In data.Rows
            purchased = row("Purchased")
            expires = row("Expires")
            If expires > DateTime.Now Then
                TS = expires.Subtract(DateTime.Now)
                row("Time Left") = String.Format("{0} days, {1} hrs, {2} mins, {3} secs", TS.Days, TS.Hours, TS.Minutes, TS.Seconds)
            Else
                row("Time Left") = "Expired!"
            End If
        Next
    End Sub

End Class

Open in new window


DataGridView instead of ListView example...
0
 
Jesus RodriguezIT ManagerCommented:
First delete your grocies.txt to see what happend and begin to add products

 I attach again the whole code and  a grocies.txt file as an example that who it write on the txt file
grocies.txt
WholeCode.txt
0
 
Jesus RodriguezIT ManagerCommented:
Yes, with the datagrid will be way faster than a listview but I don't know if later he wants to translate the code for mobile. Tha's why I let it on the Listview but the Idle solution is also a reall good one. Also you can bindit to a dataview and work with the dataview and later save the dataview and will be faster..
0
 
RobertoFreemanoAuthor Commented:
WOW that's amazing!!!! Nice work k-designers.

I've added

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        data.Rows.Add(New Object() {ComboBox1.Text, DateTime.Now, DateTimePicker1.Text, ""})
    End Sub

Open in new window


and this adds a new item.

Now just to research loading/saving DataGridView - I've never dealt with DataGridView before ;)
0
 
RobertoFreemanoAuthor Commented:
I found this code that saves to text file:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        ' save
        Dim fsStream As New FileStream("C:\tim\grocies.txt", FileMode.Create, FileAccess.Write)
        Dim swWriter As New StreamWriter(fsStream)

        Try
            For Each row As DataGridViewRow In Me.DataGridView1.Rows
                If Not row.IsNewRow Then
                    Dim values As New List(Of String)
                    For Each cell As DataGridViewCell In row.Cells
                        values.Add(CStr(cell.Value))
                    Next
                    swWriter.WriteLine(String.Join("=", values.ToArray))
                End If
            Next
            swWriter.Close()
        Catch
            swWriter.Flush()
            swWriter.Close()
            MsgBox("Saved")
        End Try
        swWriter.Close()

    End Sub

Open in new window

0
 
RobertoFreemanoAuthor Commented:
The Load button works, but not quite as I want

 
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        ' Load

        Dim filename As String
        filename = "C:\tiz\grocies.txt"

        If File.Exists(filename) Then
            Dim iofile As New StreamReader(filename)
            Dim ioline As String
            Dim _name, _value

            Dim resultsDT As New DataTable
            resultsDT.Columns.Add("Name", GetType(System.String))
            resultsDT.Columns.Add("Value", GetType(System.String))
            resultsDT.Columns.Add("Value1", GetType(System.String))
            resultsDT.Columns.Add("Value2", GetType(System.String))

            Dim i As Integer

            Do While iofile.Peek() <> -1

                ioline = iofile.ReadLine
                Dim mysplit = Split(ioline, "=")
                For i = 0 To mysplit.Count - 1
                    _name = mysplit(0)
                    _value = mysplit(1)
                    i = i + 1
                    resultsDT.Rows.Add(_name, _value)
                    DataGridView1.DataSource = resultsDT
                Next
            Loop
            iofile.Close()
        Else
            MsgBox(filename + " doesn't exist!")
        End If
    End Sub

Open in new window


I'm assuming I have to chane VALUE1 & VALUE1.
0
 
Jesus RodriguezIT ManagerCommented:
Do not get to complicate, to load the row do this

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        ' Load

         Me.DateTimePicker1.MinDate = Today

        Dim resultsDT As New DataTable
        resultsDT.Columns.Add("ITEM", GetType(System.String))
        resultsDT.Columns.Add("START DATE", GetType(System.String))
        resultsDT.Columns.Add("END DATE", GetType(System.String))
        resultsDT.Columns.Add("EXPIRE IN", GetType(System.String))

        Try
            Dim values() As String
            Dim fileName As String = "c:\tim\grocies.txt"
            Dim sr As New System.IO.StreamReader(fileName)
            Dim line As String = sr.ReadLine()
            Do Until line Is Nothing
                values = line.Split(";")
                'To add the row to the datagrid
                resultsDT.LoadDataRow(values, True)
                line = sr.ReadLine
            Loop
            sr.Close()
        Catch ex As Exception
            MsgBox("New session will start")
        End Try
        Me.DataGridView1.DataSource = resultsDT
        Me.DataGridView1.Refresh()
    End Sub



I'm doing the example with both tight to the same form for you
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Note the difference in the column creation code, though!  In my original example, the columns relating to dates/times were actually of the Type DateTime.  This can be seen in the 2nd and 3rd lines below.

My original code:
        data.Columns.Add("Item", GetType(String))
        data.Columns.Add("Purchased", GetType(DateTime))
        data.Columns.Add("Expires", GetType(DateTime))
        data.Columns.Add("Time Left", GetType(String))

Open in new window


In the modified code, all the columns have been specified as of Type String:
            resultsDT.Columns.Add("Name", GetType(System.String))
            resultsDT.Columns.Add("Value", GetType(System.String))
            resultsDT.Columns.Add("Value1", GetType(System.String))
            resultsDT.Columns.Add("Value2", GetType(System.String))

Open in new window


This means that if you want to do a date/time comparison with values from those columns you'd have to first convert from String to DateTime.  This could lead to subtle bugs as well if the local variable was also incorrectly typed as String.
0
 
Jesus RodriguezIT ManagerCommented:
Ok, here is the whole code and Also I attached the documents to it

Public resultsDT As New DataTable

    Public Sub CheckListView()
        For Each item As ListViewItem In Me.ListView1.Items
            If CDate(item.SubItems(2).Text) < Now Then 'Get the date of the item
                Dim NewIt As New ListViewItem
                NewIt.UseItemStyleForSubItems = False 'Use this line to style subitem
                NewIt.Text = item.Text
                NewIt.SubItems.Add(item.SubItems(1).Text)
                NewIt.SubItems.Add(item.SubItems(2).Text)
                NewIt.SubItems.Add("To Delete")
                Me.ListView1.Items.Add(NewIt)
                ListView1.Items.RemoveAt(item.Index)
            End If
        Next

        ListView1.Refresh()
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        If ComboBox1.Text = "" Then
        Else
            Dim pItem As New ListViewItem
            Timer1.Stop()
            pItem.UseItemStyleForSubItems = False 'Use this line to style subitem
            pItem.Text = ComboBox1.Text
            pItem.SubItems.Add(Now.ToString)
            pItem.SubItems.Add(Strings.Format(DateTimePicker1.Value, "MM/dd/yyyy") & " " & Now.TimeOfDay.ToString())
            pItem.SubItems.Add(DateDiff(DateInterval.Second, Now, CDate(DateTimePicker1.Text & " " & Now.TimeOfDay.ToString())).ToString)
            ListView1.Items.Add(pItem)
            ListView1.Refresh()

            'For the Datagrid
            resultsDT.LoadDataRow(New Object() {ComboBox1.Text, DateTime.Now, Strings.Format(DateTimePicker1.Value, "MM/dd/yyyy") & " " & Now.TimeOfDay.ToString(), DateDiff(DateInterval.Second, Now, CDate(Strings.Format(DateTimePicker1.Value, "MM/dd/yyyy") & " " & Now.TimeOfDay.ToString()))}, True)
            Me.DataGridView1.DataSource = Nothing
            Me.DataGridView1.DataSource = resultsDT
            Me.DataGridView1.Refresh()

            Timer1.Start()
        End If

    End Sub

    Private Sub EXp_Exchangevb_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        Try
            Dim myFile As String = "c:\tim\grocies.txt"
            Dim myWriter As New IO.StreamWriter(myFile)
            For Each myItem As ListViewItem In ListView1.Items
                myWriter.WriteLine(myItem.Text & ";" & myItem.SubItems(1).Text & ";" & myItem.SubItems(2).Text & ";" & myItem.SubItems(3).Text)
            Next
            myWriter.Close()
        Catch ex As Exception
            MsgBox("OOPS")
        End Try

    End Sub

    Private Sub EXp_Exchangevb_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Me.DateTimePicker1.MinDate = Today

        resultsDT.Columns.Add("ITEM", GetType(System.String))
        resultsDT.Columns.Add("START DATE", GetType(System.String))
        resultsDT.Columns.Add("END DATE", GetType(System.String))
        resultsDT.Columns.Add("EXPIRE IN", GetType(System.String))

        Try
            Dim values() As String
            Dim fileName As String = "c:\tim\grocies.txt"
            ListView1.Items.Clear()

            Dim sr As New System.IO.StreamReader(fileName)
            Dim line As String = sr.ReadLine()
            Do Until line Is Nothing
                values = line.Split(";")
                Dim NLIte As New ListViewItem
                NLIte.Text = values(0)
                For I As Integer = 1 To values.Length - 1
                    NLIte.SubItems.Add(values(I))
                Next
                ListView1.Items.Add(NLIte)
                'To add the row to the datagrid
                resultsDT.LoadDataRow(values, True)

                line = sr.ReadLine
            Loop
            sr.Close()
        Catch ex As Exception
            MsgBox("New session will start")
        End Try
        If Me.ListView1.Items.Count > 0 Then
            CheckListView()
        End If
        Me.DataGridView1.DataSource = resultsDT
        Me.DataGridView1.Refresh()
        Timer1.Interval = 10000
        Timer1.Start()
    End Sub


    Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
        If Me.ListView1.Items.Count > 0 Then 'If the listview has items
            For Each Item As ListViewItem In ListView1.Items
                Dim TimeItem As String = Item.SubItems(2).Text  'Or Text, don't rememmber
                Dim DIfference As String = DateDiff(DateInterval.Second, Now, CDate(TimeItem)).ToString
                Item.SubItems(3).Text = DIfference
            Next
        End If
        For I As Integer = 0 To resultsDT.Rows.Count - 1
            If resultsDT.Rows(I).Item(3) <> "To Delete" Then
                If DateDiff(DateInterval.Second, Now, resultsDT.Rows(I).Item(2)) <= 0 Then
                    resultsDT.Rows(I).Item(3) = "To Delete"
                Else
                    resultsDT.Rows(I).Item(3) = DateDiff(DateInterval.Second, Now, resultsDT.Rows(I).Item(2)).ToString
                End If
            End If
        Next
        Me.DataGridView1.DataSource = Nothing
        Me.DataGridView1.DataSource = resultsDT
        Me.DataGridView1.Refresh()
        Me.ListView1.Refresh()
        CheckListView()
    End Sub
grocies.txt
EXp-Exchangevb.Designer.vb
EXp-Exchangevb.resx
EXp-Exchangevb.vb
0
 
RobertoFreemanoAuthor Commented:
Hi k-designers,

I pasted your whole code into a new form and ran it... on button1 click, this error occurs:
"Conversion from string "08/30/2012 18:06:56.2470685" to type 'Date' is not valid."
I wasn't sure if I was replacing the Listview with the DataGridView?
0
 
RobertoFreemanoAuthor Commented:
Hi Mike,

I change the code to this....
Dim resultsDT As New DataTable
            resultsDT.Columns.Add("Name", GetType(System.String))
            resultsDT.Columns.Add("Value", GetType(System.String))
            resultsDT.Columns.Add("Value1", GetType(DateTime))
            resultsDT.Columns.Add("Value2", GetType(System.String))

Open in new window

and Columns 1-3  worked, but the timer failed and now I cannot get it to work at all :(
0
 
Jesus RodriguezIT ManagerCommented:
THe error that you get is because you has the the column in the Datagrid as DateTime.. If you let it as I give it to you you can work easily

        resultsDT.Columns.Add("ITEM", GetType(System.String))
        resultsDT.Columns.Add("START DATE", GetType(System.String))
        resultsDT.Columns.Add("END DATE", GetType(System.String))
        resultsDT.Columns.Add("EXPIRE IN", GetType(System.String))


Add a Datagridview and do not touch anything, let that the code do everything..Check the forms that I attach to you on previous message
FormDesign.png
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Apologies...I hadn't realized that k-designers had also used a DataTable in his solution.  Ignore my last comments.  =)
0
 
RobertoFreemanoAuthor Commented:
Hi k-designers,

Sorry for my late reply... will test today & get back to you ;)

Roberto
0
 
RobertoFreemanoAuthor Commented:
Thanks Guys ;)
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 17
  • 15
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now