vb.net System.ArgumentOutOfRangeException When Trying to ping - vb.net

been trying to follow this guide on how to make picture boxes change colour depending on if the ping has been successful or not. I have some test ip's in a CSV file that the program imports
but I keep getting a exception error. I have 3 picture boxes on the page currently defined from picturebox2 - 4
the code for the whole page is below, any suggestions or fixes would be greatly appreciated
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Threading
Imports System.IO
Imports System.Timers
Public Class Central
Dim pingTable As DataTable = New DataTable()
Dim ipAddress As List(Of String) = New List(Of String)
Dim pictureBoxList As List(Of PictureBox) = New List(Of PictureBox)
Dim timer As Timers.Timer
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
timer = New Timers.Timer
timer.Interval = 20000
timer.Enabled = True
AddHandler timer.Elapsed, AddressOf OnElapsedTime
End Sub
Private Sub OnElapsedTime(ByVal sender As Object, ByVal e As ElapsedEventArgs)
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub FillPingTable()
pingTable.Columns.Add("ip", GetType(String))
pingTable.Columns.Add("picturebox", GetType(String))
pingTable.Rows.Add()
For i As Integer = 0 To ipAddress.Count - 1
pingTable.Rows.Add(ipAddress(i), pictureBoxList(i))
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Hide()
Scot.Show()
End Sub
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
Hide()
Home.Show()
End Sub
Private Sub central_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using reader = New StreamReader("A:\IpAddress.csv")
While Not reader.EndOfStream
Dim line = reader.ReadLine
Dim values = line.Split(ChrW(10))
ipAddress.Add(values(0))
End While
For i As Integer = 1 To 2
pictureBoxList.Add(CType(Controls.Find("PictureBox" & i, True)(0), PictureBox))
FillPingTable()
BackgroundWorker1.RunWorkerAsync()
Next
End Using
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Thread.Sleep(500)
Parallel.For(0, ipAddress.Count(), Sub(i, loopState)
Dim ping As New Ping()
Dim pingReply As PingReply = ping.Send(ipAddress(i).ToString())
Me.BeginInvoke(CType(Sub()
pictureBoxList(i).SizeMode = PictureBoxSizeMode.Zoom
pictureBoxList(i).BackColor = If(pingReply.Status = IPStatus.Success, Color.Green, Color.Red)
End Sub, Action))
End Sub)
End Sub
End Class

Related

DataGridView right click event and pass-through of parameters to sub

I read a lot of things here in the forum, but I can't find a solution for my problem.
I have a DataGridView with a ContextMenu.
My aim is to call a function from the context menu and pass through parameters e.g. linenumber of selected dgv row.
Here is my code, that contains a ContextMenu, but how I could pass-through some parameters to a function?
Private Sub dataGridView1_MouseClick(ByVal sender As DataGridView, ByVal e As MouseEventArgs) Handles DataGridView1.MouseClick
If e.Button = MouseButtons.Right Then
Dim m As New ContextMenu
m.MenuItems.Add(New MenuItem("Sub1"))
m.MenuItems.Add(New MenuItem("Sub2"))
Dim currentMouseOverRow As Integer = DataGridView1.HitTest(e.X, e.Y).RowIndex
m.Show(DataGridView1, New Point(e.X, e.Y))
End If
End Sub
EDIT
Now I have got a solution that works, but I think it is not the best solution and I can do a lot of improvement.
Maybe it would be possible to code custom events, that can pass through some datas of the gridview. I hope somebody is interested to give some input to improve the following (working) code to look something like professional.
Imports System
Imports System.IO
Public Class Form1
Public gpath As String = "D:\kvt.txt"
Public Sub New()
' This call is required by the designer.
InitializeComponent()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim file = System.IO.File.ReadAllLines("d:\kvt.txt")
Dim dt As New DataTable
dt.Columns.Add("Name")
For Each line As String In file
dt.Rows.Add(line)
Next
DataGridView1.DataSource = dt
DataGridView1.Show()
End Sub
Private Sub dataGridView1_MouseClick(ByVal sender As DataGridView, ByVal e As MouseEventArgs) Handles DataGridView1.MouseClick
Dim cMenu As New ContextMenuStrip
Dim MenuItemClone As New System.Windows.Forms.ToolStripMenuItem
MenuItemClone.Text = "Clone"
cMenu.Items.Add(MenuItemClone)
If e.Button = MouseButtons.Right Then
Dim currentMouseOverRow As Integer = DataGridView1.HitTest(e.X, e.Y).RowIndex
cMenu.Show(DataGridView1, New Point(e.X, e.Y))
AddHandler MenuItemClone.Click, AddressOf CloneRepo
End If
End Sub
Private Sub CloneRepo(ByVal sender As Object, ByVal e As System.EventArgs)
Dim SelectedName As String = DataGridView1("Name", DataGridView1.CurrentCell.RowIndex).FormattedValue
End Sub
End Class
Here's an example of how you can right-click on a cell in a DataGridView and then perform an action relative to that cell when you click a menu item:
Private lastClickedCell As DataGridViewCell
Private Sub DataGridView1_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseClick
If e.ColumnIndex >= 0 AndAlso
e.RowIndex >= 0 Then
lastClickedCell = DataGridView1.Item(e.ColumnIndex, e.RowIndex)
End If
End Sub
Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick
If e.Button = MouseButtons.Right AndAlso
DataGridView1.HitTest(e.X, e.Y).Type = DataGridViewHitTestType.Cell Then
'Display the menu when right-clicking on a cell.
ContextMenuStrip1.Show(DataGridView1, e.Location)
End If
End Sub
Private Sub ClearToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ClearToolStripMenuItem.Click
'Clear the cell that was right-clicked.
lastClickedCell.Value = Nothing
End Sub
The ContextMenuStrip was created in the designer for this example. I would recommend doing that in your case too, even if you need to choose items dynamically. You can clear the menu and add and/or remove items in the CellMouseClick or MouseClick event handlers of the grid, or the Opening event handler of the menu.
Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick
Dim col As New DataGridTextBoxColumn
If e.Button = MouseButtons.Right Then
Dim m As New ContextMenuStrip
col.TextBox.ContextMenuStrip = m
Dim tsp As New ToolStripMenuItem("Sub1", Nothing, New EventHandler(AddressOf TestMessage))
Dim tsp1 As New ToolStripMenuItem("Sub2", Nothing, New EventHandler(AddressOf TestMessage))
m.Name = "Menulist"
m.Items.Add(tsp)
m.Items.Add(tsp1)
Dim currentMouseOverRow As Integer = DataGridView1.HitTest(e.X, e.Y).RowIndex
m.Show(DataGridView1, New Point(e.X, e.Y))
End If
End Sub
Private Sub TestMessage()
MessageBox.Show("Clicked")
End Sub
try this and use 'Tag':
Dim currentMouseOverRow As Integer
Structure MyStructure
Public x As Integer
Public y As Integer
End Structure
Private Sub DataGridView1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseClick
Dim Mystruct As MyStructure
If e.Button = Windows.Forms.MouseButtons.Right Then
Dim m As New System.Windows.Forms.ContextMenuStrip
Dim MymenuToolStripMenuItem1 As New System.Windows.Forms.ToolStripMenuItem
MymenuToolStripMenuItem1.Text = "menu1"
AddHandler MymenuToolStripMenuItem1.Click, AddressOf MymenuToolStripMenuItem1_Click
m.Items.Add(MymenuToolStripMenuItem1)
Dim MymenuToolStripMenuItem2 As New System.Windows.Forms.ToolStripMenuItem
MymenuToolStripMenuItem2.Text = "menu2"
AddHandler MymenuToolStripMenuItem2.Click, AddressOf MymenuToolStripMenuItem2_Click
m.Items.Add(MymenuToolStripMenuItem2)
Mystruct.x = e.X
Mystruct.x = e.X
MymenuToolStripMenuItem2.Tag = Mystruct
currentMouseOverRow = DataGridView1.HitTest(e.X, e.Y).RowIndex
m.Show(DataGridView1, New Point(e.X, e.Y))
End If
End Sub
Private Sub MymenuToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
MessageBox.Show("click Menu1:" & currentMouseOverRow)
End Sub
Private Sub MymenuToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim Mystruct As MyStructure
Mystruct = CType(CType(sender, System.Windows.Forms.ToolStripMenuItem).Tag, MyStructure)
MessageBox.Show("click Menu2:" & currentMouseOverRow & " x:" & Mystruct.x & " y:" & Mystruct.y)
End Sub

Updating progress bar from threadpool

Im trying to update a progress bar in my main form from a threadpool but everything Iv'e tried so far updates the value of the progress bar but not the physical appearance of it, Tried several different ways and still can't find a solution. Can someone please point me in the right direction to update the progress bar on my form1 by 1 every time a thread has completed.
Imports System.Threading
Public Class Form1
Dim arry As New List(Of String)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
BackgroundWorker1.RunWorkerAsync()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim ii As Integer = 2000
For a As Integer = 0 To ii
arry.Add(a)
Next
ProgressBar1.Maximum = arry.Count
ThreadPool.SetMaxThreads(4, 4)
Dim doneEvents(arry.Count) As ManualResetEvent
Dim r As New Random()
For i As Integer = 0 To arry.Count
doneEvents(i) = New ManualResetEvent(False)
Dim f = New stuff(r.Next(20, 40), doneEvents(i))
ThreadPool.QueueUserWorkItem(AddressOf f.ThreadPoolCallBack, i)
Next
For Each handle As WaitHandle In doneEvents
handle.WaitOne()
Next
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckForIllegalCrossThreadCalls = False
End Sub
Private Delegate Sub FillDelegate()
Public Sub Fill()
If ProgressBar1.InvokeRequired Then
ProgressBar1.BeginInvoke(New FillDelegate(AddressOf Fill))
Else
ProgressBar1.Increment(1)
ProgressBar1.Refresh()
End If
End Sub
End Class
Public Class stuff
Private _doneEvent As ManualResetEvent
Private _n As Integer
Public ReadOnly Property N() As Integer
Get
Return _n
End Get
End Property
Sub New(ByVal n As Integer, ByVal doneEvent As ManualResetEvent)
_n = n
_doneEvent = doneEvent
End Sub
Public Sub ThreadPoolCallBack(ByVal threadContext As Object)
Try
Dim threadIndex As Integer = CType(threadContext, Integer)
Console.WriteLine("thread {0} started...", threadIndex)
Form1.Fill()
Console.WriteLine("thread {0} finished...", threadIndex)
Catch ex As Exception
Console.WriteLine("error in threadPoolCallback")
Console.WriteLine(ex.Message)
Finally
_doneEvent.Set()
End Try
End Sub
End Class

How do get only available ssid with visual basic 2010

Sorry for bad english
I want the available ssid list in listbox
I am use api and its work but It stopped working after a while.And not see current wifi list.
My code:
Imports deneme2.NativeWifi
Imports System.Text
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Timer1.Start()
End Sub
Private Sub scan()
On Error Resume Next
Dim client As New WlanClient
ListView1.Items.Clear()
For Each wlanIface As WlanClient.WlanInterface In client.Interfaces
Dim networks() As Wlan.WlanAvailableNetwork = wlanIface.GetAvailableNetworkList(0)
For Each network As Wlan.WlanAvailableNetwork In networks
Dim ssid As Wlan.Dot11Ssid = network.dot11Ssid
Dim networkName As String = Encoding.ASCII.GetString(ssid.SSID, 0, CType(ssid.SSIDLength, Integer))
Dim item As ListViewItem = New ListViewItem(networkName)
item.SubItems.Add(network.dot11DefaultCipherAlgorithm.ToString())
item.SubItems.Add(network.wlanSignalQuality.ToString + "%")
ListView1.Items.Add(item)
Next
Next
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
scan()
End Sub
End Class

VB.NET Create and Close Forms after Certain Time

I could easily close form after few seconds; but when I want to close many forms one after another, same sequence as they were "created"; I could not figure it out:
The main form code is as below:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim numberOfForms As Integer = 10
For open = 1 To numberOfForms
TestClosing()
Next
End Sub
The module code that I am trying to create then close forms after few seconds is as below:
Imports System.Timers
Module ClosingModule
Sub TestClosing()
Dim frmNew As New Form
frmNew.Show()
Dim tmr As New System.Timers.Timer()
tmr.Interval = 3000
tmr.Enabled = True
tmr.Start()
End Sub
End Module
I started a timer, but all the methods I tried to close the form is same sequence they were created; were not successful;
Help appreciated; and thanks in advance.
Add the Timer to the Forms you are creating, start it when the Form is created that way they will be closed in the same order that they were created. I also added an incremental delay to that the order of closing is more evident.
Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim numberOfForms As Integer = 10
For open = 1 To numberOfForms
Dim frmNew As New Form2
frmNew.Text = open.ToString
frmNew.Show()
Next
End Sub
Form2
Public Class Form2
Dim myTimer As New Timer()
Private Sub myTimer_Tick(sender As System.Object, e As System.EventArgs)
myTimer.Stop()
Me.Close()
End Sub
Private Sub Form2_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
myTimer.Interval = 1000 * CInt(Me.Text)
AddHandler myTimer.Tick, AddressOf myTimer_Tick
myTimer.Start()
End Sub
End Class
Added code in module to do the same thing:
Imports System.Timers
Module ClosingModule
Sub TestClosing(multiplier As Integer)
Dim frmNew As New Form
frmNew.Show()
Dim tmr As New System.Timers.Timer()
AddHandler tmr.Elapsed, AddressOf Timer_Elapsed 'Add Handler to New Timer
tmr.SynchronizingObject = frmNew 'Synchronize Timer to newly created form
tmr.Interval = 1000 * multiplier
tmr.Enabled = True
tmr.Start()
End Sub
Public Sub Timer_Elapsed(sender As Object, e As ElapsedEventArgs)
Dim tmr As System.Timers.Timer = DirectCast(sender, System.Timers.Timer)
tmr.Stop() 'Stop Timer
DirectCast(tmr.SynchronizingObject, Form).Close() 'Get Form Timer was synchronized with and close it
tmr.SynchronizingObject = Nothing 'Remove Form reference from timer
RemoveHandler tmr.Elapsed, AddressOf Timer_Elapsed 'Remove Handler from Timer
End Sub

vb2012 textbox backcolor does't change using thread

I wrote very simple thread example.
Make normal form1 and drop 1 textbox
run thread work on form load
thread change a textbox backcolor looks like switch on/off
But, it doesn't work.....
Can you tell me why doesn't work??
see my source.
=====================================================================
Imports System.Threading
Public Class Monitor
Public wObj As Worker = New Worker()
Public MyThread As Thread = New Thread(AddressOf wObj.DoWork)
Public Sub ChangeTBColor(pOption As Integer)
If pOption = 1 Then
tb1.BackColor = Color.Aqua
Else
tb1.BackColor = Color.Red
End If
End Sub
Private Sub Monitor_Load(sender As Object, e As EventArgs) Handles Me.Load
MyThread.Start()
Console.WriteLine("Running OrgThread..")
Console.WriteLine("Stop running")
End Sub
Private Sub BtnThreadStop_Click(sender As Object, e As EventArgs) Handles BtnThreadStop.Click
Me.wObj.RequestStop()
End Sub
End Class
Public Class Worker
Private LoopStop As Boolean = True
Public Sub DoWork()
Console.WriteLine("User Thread Start!")
Dim iTemp As Integer = 0
While (LoopStop)
Monitor.ChangeTBColor(iTemp Mod 2)
iTemp = iTemp + 1
Thread.Sleep(500)
End While
Console.WriteLine("User Thread End.!")
End Sub
Public Sub RequestStop()
LoopStop = False
End Sub
End Class
As already mentioned, your starting a new thread for your work, the issue is your trying to change the color for a control that need invoking. With this said, we need a delegate for when the control needs to be invoked... In my example, I used one class that handles this all and works great. Also please make sure to import System.ComponentModel because this is needed for the BackgroundWorker... I used the background worker as it takes all the heavy lifting off you would need...
Imports System.ComponentModel
Imports System.Threading
Public Class Monitor
Delegate Sub SetColor(ByVal clr As Integer) 'Your delegate..
Private WithEvents bw As New BackgroundWorker
Public Sub ChangeTBColor(pOption As Integer)
If Me.tb1.InvokeRequired Then 'Invoke if required...
Dim d As New SetColor(AddressOf ChangeTBColor) 'Your delegate...
Me.Invoke(d, New Object() {pOption})
Else
If pOption = 1 Then
tb1.BackColor = Color.Aqua
Else
tb1.BackColor = Color.Red
End If
End If
End Sub
Private Sub Monitor_Load(sender As Object, e As EventArgs) Handles Me.Load
bw.WorkerSupportsCancellation = True
Console.WriteLine("Running OrgThread..")
bw.RunWorkerAsync()
End Sub
Private Sub bw_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bw.DoWork
Dim iTemp As Integer = 0
Dim LoopStop As Boolean = True
Console.WriteLine("User Thread Start!")
While (LoopStop)
If Not (bw.CancellationPending) Then
ChangeTBColor(iTemp Mod 2)
iTemp = iTemp + 1
Thread.Sleep(500)
Else
e.Cancel = True
LoopStop = False
End If
End While
End Sub
Private Sub bw_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bw.RunWorkerCompleted
Console.WriteLine("User Thread End.!")
End Sub
Private Sub BtnThreadStop_Click(sender As Object, e As EventArgs) Handles BtnThreadStop.Click
If bw.IsBusy Then
bw.CancelAsync()
Else
Console.WriteLine("Running OrgThread..")
bw.RunWorkerAsync()
End If
End Sub
End Class
Here's my screenshot of my test... This is tried and tested. Please be sure to vote if this helps you!