How to check if Variable value is increaseing vb.net? - vb.net

Hi I have listview and lable ,the lable is showing how many items in the listview
I want if the lable is increased will show msgbox
* may be it will increased alot such as 100 or 1 whatever
* It will execute the command just one if the value is increased
* it must be execute the msgbox any time if the value is increased
I'm sorry for my bad language
thank you
the code :
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim b As String = New WebClient().DownloadString(TextBox2.Text + "/Getinfo.php")
Dim mc As MatchCollection = Regex.Matches(b, "(\w+):")
For Each x As Match In mc
Dim infoName As String = x.Groups(1).Value
Try
Dim download As String = New WebClient().DownloadString(TextBox2.Text + "/sender/info/" & infoName & "/info.txt")
Dim f As String() = download.Split(":")
Dim ls As New ListViewItem
ls.Text = infoName
For Each _x As String In f
ls.SubItems.Add(_x)
Next
Dim hTable As Hashtable = New Hashtable()
Dim duplicateList As ArrayList = New ArrayList()
Dim itm As ListViewItem
For Each itm In ListView1.Items
If hTable.ContainsKey(itm.Text) Then 'duplicate
duplicateList.Add(itm)
Else
hTable.Add(itm.Text, String.Empty)
End If
Next
'remove duplicates
For Each itm In duplicateList
itm.Remove()
Next
ListView1.Items.Add(ls)
'here I want to excute the command if the value is increased but it's timer and the code will be execute every time
Catch
End Try
Next
End Sub

At the top of your function do
Dim oldlength = ListView1.Items.Count
At the bottom do
If oldlength < ListView1.Items.Count Then
'here I want to excute the command if the value is increased
End If
I'm pretty sure that your MessageBox isn't really what you want but a debugging example because you think if you can get the MessageBox at the right time you've solved one of your problems (which is true).

Related

How to match last line of text file in treeview and display text boxes in vb.net?

I have a problem with a sorted TreeView. I select the last line of a text file, then I extract from this text file the last child node added in the TreeView. Where the shoe pinch is that I can't do it! I have tried with the number of lines in this file, but no results. In fact, I do a bit of everything (not of course) to get the selected node to coincide in the treeview and the displays in the text boxes. Below is a screenshot and my code! I don't know if I made myself understood correctly, my English is translated English. Thank you. Claude.
Dim NbLine As Integer = 0
Dim SR As System.IO.StreamReader = New System.IO.StreamReader(OuvrirFichier)
While Not SR.EndOfStream
SR.ReadLine()
NbLine += 1
End While
SR.Close()
Dim lastLine As String = File.ReadLines(OuvrirFichier, Encoding.UTF8) _
.Where(Function(f As String) (Not String.IsNullOrEmpty(f))).Last.ToString
Dim mytext As String = lastLine.Substring(17, 90)
If NbLine > 0 Then
Dim lignesDuFichier As String() = File.ReadAllLines(OuvrirFichier, Encoding.UTF8)
Dim derniereLigne As String = lignesDuFichier(lignesDuFichier.Length - 1)
TreeView1.Focus()
TreeView1.SelectedNode = TreeView1.Nodes(0).Nodes(lignesDuFichier.Length - 1)
End If
Comments in line.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim OuvrirFichier = "C:\Users\maryo\Desktop\Code\Test Empty Line.txt" '"path to file"
'At least you will only be reading the file once
Dim AllLines = File.ReadAllLines(OuvrirFichier)
Dim LinesWithContent = AllLines.Where(Function(s) s.Trim() <> String.Empty)
Dim lastLine = LinesWithContent.Last
Dim mytext As String = lastLine.Substring(17, 90)
Debug.Print(mytext) 'Just checking that you get what was expected
Dim NbLine = AllLines.Length
Dim derniereLigne As String = AllLines(NbLine - 1) 'Another variable to hold last line???
'But this time it could be a blank line.
TreeView1.Focus()
'This makes no sense. An index of a subNode base on the number of lines in the text file
'is supposed to be the SelectedNode
'Why would this be the last node added?
TreeView1.SelectedNode = TreeView1.Nodes(0).Nodes(NbLine - 1)
'You never test the equality of the SelectedNode with mytext
End Sub

Output random lines from a large document to a TextBox

I'm trying to make a program that reads a large document, for example the bible, and outputs multiple random lines. I can get it to output one random line, but no others.
The end goal is to have a user input to determine how many lines are displayed.
Here's my code:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Dim howmanylines As Integer
' howmanylines = InputBox("how many lines for paragrpah", "xd",,,)
'Dim count As Integer = 0
' Do Until count = howmanylines
Dim sr As New System.IO.StreamReader("C:\Users\Dumpster Fire\Desktop\bible.doc")
Dim sr2 As New System.IO.StreamReader("C:\Users\Dumpster Fire\Desktop\bible.doc")
Dim sr3 As New System.IO.StreamReader("C:\Users\Dumpster Fire\Desktop\bible.doc")
Dim xd As Integer = 0
Dim curline As Integer = 0
Dim random As Integer = 0
Do Until sr.EndOfStream = True
sr.ReadLine()
xd = xd + 1
Loop
sr.Dispose()
sr.Close()
Randomize()
random = Rnd() * xd
Do Until curline = random
TextBox1.Text = sr2.ReadLine
' curline = curline + 1
Randomize()
random = Rnd() * xd
TextBox1.Text = sr3.ReadLine
curline = curline + 1
' count = count + 1
Loop
End Sub
End Class
A couple of things I would suggest to improve your code.
Implement Using. This will ensure that the StreamReader is disposed of when finished. It saves you having to remember and it's less lines of code so improves readability.
I would consider using Integer.TryParse:
Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.
You only need to use one StreamReader and add all the lines to a List(Of String).
Use a StringBuilder to add your lines too and then output this to the TextBox at the end. Note that you will have to import System.Text to reference the StringBuilder class.
Use Random.Next:
Returns a random integer that is within a specified range.
The end result would be something like this:
txtLines.Text = ""
Dim howManyLines As Integer = 0
If Integer.TryParse(txtUserInput.Text, howManyLines) Then
Dim lines As New List(Of String)
Using sr As New StreamReader("C:\test\test.txt")
Do Until sr.EndOfStream()
lines.Add(sr.ReadLine)
Loop
End Using
Dim sb As New StringBuilder
Dim rnd As New Random()
For i = 0 To howManyLines - 1
Dim nextLine As Integer = rnd.Next(lines.Count - 1)
sb.AppendLine(lines(nextLine))
Next
txtLines.Text = sb.ToString()
End If
You would ideally place this code on a button click event.

Change label text in foreach loop

i want to update a label while a foreach-loop.
The problem is: the program waits until the loop is done and then updates the label.
Is it possible to update the label during the foreach-loop?
Code:
Dim count as Integer = 0
For Each sFile as String in Files
'ftp-code here, works well
count = count+1
progressbar1.value = count
label1.text = "File " & count & " of 10 uploaded."
next
Thanks in advance
Label is not updated because UI thread is blocked while executing your foreach loop.
You can use async-await approach
Private Async Sub Button_Click(sender As Object, e As EventArgs)
Dim count as Integer = 0
For Each sFile as String in Files
'ftp-code here, works well
count = count+1
progressbar1.value = count
label1.text = "File " & count & " of 10 uploaded."
Await Task.Delay(100)
Next
End Sub
Because you will work with Ftp connections, which is perfect candidate for using async-await.
The Await line will release UI thread which will update label with new value, and continue from that line after 100 milliseconds.
If you will use asynchronous code for ftp connection , then you don't need Task.Delay
You've already accepted an answer but just as an alternative a BackgroundWorker can also be used for something like this. In my case the FTP to get the original files happens very quickly so this snippet from the DoWork event is for downloading those files to a printer.
Dim cnt As Integer = docs.Count
Dim i As Integer = 1
For Each d As String In docs
bgwTest.ReportProgress(BGW_State.S2_UpdStat, "Downloading file " & i.ToString & " of " & cnt.ToString)
Dim fs As New IO.FileStream(My.Application.Info.DirectoryPath & "\labels\" & d, IO.FileMode.Open)
Dim br As New IO.BinaryReader(fs)
Dim bytes() As Byte = br.ReadBytes(CInt(br.BaseStream.Length))
br.Close()
fs.Close()
For x = 0 To numPorts - 1
If Port(x).IsOpen = True Then
Port(x).Write(bytes, 0, bytes.Length)
End If
Next
If bytes.Length > 2400 Then
'these sleeps are because it is only 1-way comm to printer so I have no idea when printer is ready for next file
System.Threading.Thread.Sleep(20000)
Else
System.Threading.Thread.Sleep(5000)
End If
i = i + 1
Next
In the ReportProgress event... (of course, you need to set WorkerReportsProgress property to True)
Private Sub bgwTest_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bgwTest.ProgressChanged
Select Case e.ProgressPercentage
'BGW_State is just a simple enum for the state,
'which determines which UI controls I need to use.
'Clearly I copy/pasted from a program that had 15 "states" :)
Case BGW_State.S2_UpdStat
Dim s As String = CType(e.UserState, String)
lblStatus.Text = s
lblStatus.Refresh()
Case BGW_State.S15_ShowMessage
Dim s As String = CType(e.UserState, String)
MessageBox.Show(s)
End Select
End Sub
Is it not enough to use Application.DoEvents()? This clears the build up and you should be able to see the text fields being updated very quickly.

how to check checklistbox items using datagridview vb.net?

I'm just a beginner for coding and I want to programmatically check items in checklistbox using datagridview.
Data grid view values are seperated with commas like this jhon,Metilda,saman,.
Checklistbox name as chklistinput and please help me to solve this ?
'Full coding is here..............................
Private Sub TextBox10_TextChanged(sender As Object, e As EventArgs) Handles TextBox10.TextChanged
'this is ok and searching as I want
Dim SearchV As String = TextBox10.Text
SearchV = "%" + TextBox10.Text + "%"
Me.PassIssuingRecordTableAdapter.FillBy(Me.Database4DataSet.PassIssuingRecord, SearchV)
'But the problem bigins here
Dim areasback As String = DataGridView1.Rows(0).Cells(6).Value.ToString
Dim areasback1 As String() = areasback.Split(",")
For Each x In areasback1
For i = 0 To areasback.Count - 1
If chklistInput.Items(i).ToString() = x.ToString() Then
chklistInput.SetItemChecked(i, False)
End If
Next
Next
End Sub
You have to loop over chklistInput.Items.Count - 1 instead of areasback.Count - 1
use the following code:
Dim areasback As String = DataGridView1.Rows(0).Cells(6).Value.ToString
Dim areasback1 As String() = areasback.Split(",")
Dim intCount as integer = 0
For each str as string in areasback1
For intCount = 0 To chklistInput.Items.Count - 1
If chklistInput.Items(intCount).ToString() = str Then
chklistInput.SetItemChecked(intCount , True)
End If
Next
Next
chklistInput.Refresh()
Note: comparing is case sensitive

VB "Index was out of range, must be non-negative and less than the size of the collection." When trying to generate a random number more than once

So I'm trying to generate a random number on button click. Now this number needs to be between two numbers that are inside my text file with various other things all separated by the "|" symbol. The number is then put into the text of a textbox which is being created after i run the form. I can get everything to work perfectly once, but as soon as i try to generate a different random number it gives me the error: "Index was out of range, must be non-negative and less than the size of the collection." Here is the main code as well as the block that generates the textbox after loading the form. As well as the contents of my text file.
Private Sub generate()
Dim newrandom As New Random
Try
Using sr As New StreamReader(itemfile) 'Create a stream reader object for the file
'While we have lines to read in
Do Until sr.EndOfStream
Dim line As String
line = sr.ReadLine() 'Read a line out one at a time
Dim tmp()
tmp = Split(line, "|")
rows(lineNum).buybutton.Text = tmp(1)
rows(lineNum).buyprice.Text = newrandom.Next(tmp(2), tmp(3)) 'Generate the random number between two values
rows(lineNum).amount.Text = tmp(4)
rows(lineNum).sellprice.Text = tmp(5)
rows(lineNum).sellbutton.Text = tmp(1)
lineNum += 1
If sr.EndOfStream = True Then
sr.Close()
End If
Loop
End Using
Catch x As Exception ' Report any errors in reading the line of code
Dim errMsg As String = "Problems: " & x.Message
MsgBox(errMsg)
End Try
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
rows = New List(Of duplicate)
For dupnum = 0 To 11
'There are about 5 more of these above this one but they all have set values, this is the only troublesome one
Dim buyprice As System.Windows.Forms.TextBox
buyprice = New System.Windows.Forms.TextBox
buyprice.Width = textbox1.Width
buyprice.Height = textbox1.Height
buyprice.Left = textbox1.Left
buyprice.Top = textbox1.Top + 30 * dupnum
buyprice.Name = "buypricetxt" + Str(dupnum)
Me.Controls.Add(buyprice)
pair = New itemrow
pair.sellbutton = sellbutton
pair.amount = amounttxt
pair.sellprice = sellpricetxt
pair.buybutton = buybutton
pair.buyprice = buypricetxt
rows.Add(pair)
next
end sub
'textfile contents
0|Iron Sword|10|30|0|0
1|Steel Sword|20|40|0|0
2|Iron Shield|15|35|0|0
3|Steel Shield|30|50|0|0
4|Bread|5|10|0|0
5|Cloak|15|30|0|0
6|Tent|40|80|0|0
7|Leather Armour|50|70|0|0
8|Horse|100|200|0|0
9|Saddle|50|75|0|0
10|Opium|200|500|0|0
11|House|1000|5000|0|0
Not sure what else to add, if you know whats wrong please help :/ thanks
Add the following two lines to the start of generate():
Private Sub generate()
Dim lineNum
lineNum = 0
This ensures that you don't point to a value of lineNum outside of the collection.
I usually consider it a good idea to add
Option Explicit
to my code - it forces me to declare my variables, and then I think about their initialization more carefully. It helps me consider their scope, too.
Try this little modification.
I took your original Sub and changed a little bit take a try and let us know if it solve the issue
Private Sub generate()
Dim line As String
Dim lineNum As Integer = 0
Dim rn As New Random(Now.Millisecond)
Try
Using sr As New StreamReader(_path) 'Create a stream reader object for the file
'While we have lines to read in
While sr.Peek > 0
line = sr.ReadLine() 'Read a line out one at a time
If Not String.IsNullOrEmpty(line) And Not String.IsNullOrWhiteSpace(line) Then
Dim tmp()
tmp = Split(line, "|")
rows(lineNum).buybutton.Text = tmp(1)
rows(lineNum).buyprice.Text = rn.Next(CInt(tmp(2)), CInt(tmp(3))) 'Generate the random number between two values
rows(lineNum).amount.Text = tmp(4)
rows(lineNum).sellprice.Text = tmp(5)
rows(lineNum).sellbutton.Text = tmp(1)
lineNum += 1
End If
End While
End Using
Catch x As Exception ' Report any errors in reading the line of code
Dim errMsg As String = "Problems: " & x.Message
MsgBox(errMsg)
End Try
End Sub