[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1471
  • Last Modified:

VB.NET - update Listview Items

Hi Experts,

I'm trying to build an small app that will tell me when my groceries are about to expire.
My winform has:
1. Listview
2. Combobox
3. Label
4. Timer
5. DateTimePicker1
6. Button

on Form load - Listview loads in text file data in format of:
Carrots;date stamp
Ham;date stamp

date stamp comes from a DateDateTimePicker1 which then is saved to textfile.

I plan to add items to the listview as i go along - this will ofcourse save to the textfile.

I found some code online:

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

Open in new window

You can see, this counts  down from Todays date.

If I button click to add an Item to my list:
combox1 = Grocery item
Date

 Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        If ComboBox1.Text = "" Then
            MsgBox("OI")
        Else
            Dim pItem As ListViewItem
            pItem = New ListViewItem
            pItem.UseItemStyleForSubItems = False 'Use this line to style subitem
            pItem.Text = ComboBox1.Text
            pItem.SubItems.Add(Label1.Text)
            ListView1.Items.Add(pItem)
        End If

        If DateTimePicker1.Text < Today Then
            MsgBox("cannot")
        Else
            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 If

    End Sub

Open in new window

WHY DO I DECLARE SAME VALUES ON BUTTON_CLICK AND TIMER1?????
because i get the following error:

System.InvalidOperationException was unhandled
  Message=An error occurred creating the form. See Exception.InnerException for details.  The error is: Object reference not set to an instance of an object.

The aim is to:
A:) restrict DateTimePicker1 to choose past date...only Future date.
B:) Refresh Listview on Button click
C:) If Item expires by date - message to delete item.

My head hurts - can someone please advise on better way to do this ;)

Thanks,
Roberto
0
RobertoFreemano
Asked:
RobertoFreemano
  • 9
  • 7
  • 2
2 Solutions
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
The error is probably at this line in your Timer code:

    Dim enddate As Date = Date.Parse(DateTimePicker1.Text)

...because DateTimePicker1 doesn't have selected value and therefore the Date.Parse() call fails.

Why not add another column to your ListView that has the remaining time for each item.  Then, in your Timer code, you can iterate over the items and update each one individually?
0
 
RobertoFreemanoAuthor Commented:
Hi Mike,

Remaining time you say...I thought Label1 showed this... forgive me, I'm probably being a thicko :(
0
 
Jesus RodriguezIT ManagerCommented:
A:) restrict DateTimePicker1 to choose past date...only Future date.
C:) If Item expires by date - message to delete item.

On Form Load

   Public Sub LoadTmp()
        Me.DateTimePicker3.MinDate = Today
        CheckListViewListView()
    End Sub

 Public Sub CheckListViewListView()
        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


B:) Refresh Listview on Button click

On the Button Click to Add the 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(Label1.Text)
            ListView1.Items.Add(pItem)
        End If
       Listview1.refresh()
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
RobertoFreemanoAuthor Commented:
Hi k-designers,

Thanks for your response... I've tested your code and it allows yesterdays date :(

Good effort though :)
Can't wait to test this bit
If CDate(item.SubItems(0).Text) < Today Then....

Roberto
0
 
RobertoFreemanoAuthor Commented:
Hi Mike,

I now have 3 columns
ITEM | Today | End Date

I guess I want enddate to work out the figure from Today... so, DateTimePicker will only be for exipry date... working on this
0
 
Jesus RodriguezIT ManagerCommented:
That's weird?? When you add MinDate to the Datetimepicker on the form load event let you select Yesterday?? Check the properties of the datetimepicker as is

MinDate='08/27/2012'
Format=Short


Then Set It again on the FormLoad Event as

DatetimePicker1.MinDate='Today.date
DatettmePicker1.refresh()

Must be showing the datetimepicker as blank for previuos date. Check your system date also.
0
 
Jesus RodriguezIT ManagerCommented:
That's how it shows on the test form that I created
11.png
0
 
RobertoFreemanoAuthor Commented:
Hi k-designers,

Will check... also, VB added this line...
Private Sub CheckListViewListView1()
        Throw New NotImplementedException
    End Sub

Open in new window

in order to accept
CheckListViewListView()

Open in new window

Do you think this will affect anything?
0
 
RobertoFreemanoAuthor Commented:
Adding:
DatetimePicker1.MinDate= Today.date
DatetimePicker1.refresh()
Sorted out the issue with DatetimePicker1 - Thankyou k-designers,

;)
0
 
Jesus RodriguezIT ManagerCommented:
Delete this Lines.. You already have the code for this.. The Clean Code will Be

Public Sub  Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load        
        Me.DateTimePicker1.MinDate = Today
        Me.DateTimePicker1.Refresh()
        CheckListView()
 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



'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(Label1.Text)
            ListView1.Items.Add(pItem)
        End If
       Listview1.refresh()
End Sub
0
 
RobertoFreemanoAuthor Commented:
I think it's looking good ;)

just to wrap up with the refresh (bit)

I want to check my grocies list, every other day...

So I use:
' load into Listview1
        Try
            Dim values() As String
            Dim fileName As String = "c:\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("Error")
        End Try

Open in new window

Sorry, this is the only code I have to load into Listview... which seems to work.

I then select from combobox and click to add to Listview1

The grocies.txt holds a list of grocies;datastamp...

I need this to save/update every now & then... either timer or button... I'm sure i can sort out this bit...

I use:
 Dim myFile As String = "c:\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)
        Next
        myWriter.Close()

Open in new window


to write to the file... this way, if any items expire and are removed... it will update the txt file... does this make sense... if there a better way of doing this?
0
 
Jesus RodriguezIT ManagerCommented:
You can do this on the Form Close event or when the ListView get's checked to see the expiration date and then will be dynamically populate or re-arrenge the list on the text
0
 
Jesus RodriguezIT ManagerCommented:
On this Event for the button Add you can add this

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(Label1.Text)
            ListView1.Items.Add(pItem)
        End If
       CheckListView()
       Listview1.refresh()
   
    'Your code here
    'That will dynamically be updating the text
        Dim myFile As String = "c:\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)
        Next
        myWriter.Close()

End Sub
0
 
RobertoFreemanoAuthor Commented:
Thanks k-designers,

You've been great ;)

I realise my error, what I'm trying to do won't work. I just relised it...

I want to load txt file of groceries in to Listview1 as:
Carrots;date stamp count-down
Beans;date stamp count-down
etc...

But i'm trying to refresh the "date stamp count-down" in subitem... and i don't this can be done from a text file...
0
 
RobertoFreemanoAuthor Commented:
Thanks Guys... I'll pursue this with a little more thought ;)
0
 
Jesus RodriguezIT ManagerCommented:
You can do a trick,
- Gets when the form Open the list with the time stamp.
- Add a timer to the form
- When the timer tick then update only the time stamp values on the items for the listview subitems (1)
- when the form close stop the timer and update the list with the last timestamp value that you have on the list box
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
*Been out so I haven't followed everything that transpired...

"But i'm trying to refresh the "date stamp count-down" in subitem... and i don't this can be done from a text file..."

Right...you would store the date bought and the expiration date in the text file.

The count-down is dynamic and would be calculated at run-time with each Timer Tick() so it can be updated in the ListView only; you wouldn't write the countdown back out to the file.
0
 
RobertoFreemanoAuthor Commented:
Thanks Guys.... I'm going to open a new call and see if we can dynamically calculate at run-time with each Timer Tick()  ;)
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 9
  • 7
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now