Hello this is my first time posting here. well to the point, I have pieced together
a app that is able to load a text file, add on the fly to a "listbox", now all i need it to Ping all ips in said "listbox" but i get an error and stops working. need help to ping all ips.
Private Sub Go_Click(sender As Object, e As EventArgs) Handles Go.Click
If ListBox1.Items.Count <= 0 Then
MsgBox("Please Add at Least One IP or Website!")
Exit Sub
End If
For l_index As Integer = 0 To ListBox1.Items.Count - 1 'THIS IS WHERE CODE STOPS WORKING, NEED "MAGIC CODE" HERE
Dim lines As String = CStr(ListBox1.Items(l_index))
BackgroundWorker1.RunWorkerAsync(lines)
Next
End Sub
I am using Openfiledialog to load Text File to listbox1 and backgroundworker to do the ping. I am using
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Threading
Imports System.IO
What i want to do is once that all "IPs" are in the listbox i want to press Go to Ping all Ips. How can i get this to work?
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Threading
Imports System.IO
Public Class Main
Private Sub AboutUpingToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutUpingToolStripMenuItem.Click
AboutUping.Show()
End Sub
Private Sub MenuStrip1_ItemClicked(sender As Object, e As ToolStripItemClickedEventArgs) Handles MainMenu.ItemClicked
End Sub
Private Sub QuitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles QuitToolStripMenuItem.Click
Application.Exit()
End Sub
Private Sub OpenFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim lines = File.ReadAllLines(OpenFileDialog1.FileName)
ListBox1.Items.AddRange(lines)
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
OpenFileDialog1.ShowDialog()
End Sub
Private Sub NewToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewToolStripMenuItem.Click
Create.Show()
End Sub
Private Sub ToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem1.Click
End Sub
Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Go_Click(sender As Object, e As EventArgs) Handles Go.Click
If ListBox1.Items.Count <= 0 Then
MsgBox("Please Add at Least One IP or Website!")
Exit Sub
End If
For l_index As Integer = 0 To ListBox1.Items.Count - 1 'THIS IS WHERE CODE STOPS WORKING, NEED "MAGIC CODE" HERE
Dim lines As String = CStr(ListBox1.Items(l_index))
BackgroundWorker1.RunWorkerAsync(lines)
Next
End Sub
Private Sub CloseFileToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CloseFileToolStripMenuItem.Click
TextBox1.Clear()
ListBox1.Items.Clear()
End Sub
Private Sub cmdADD_Click(sender As Object, e As EventArgs) Handles cmdADD.Click
Dim myitem
myitem = txtADD.Text()
ListBox1.Items.Add(myitem)
txtADD.Clear()
End Sub
Private Sub cmdRemove_Click(sender As Object, e As EventArgs) Handles cmdRemove.Click
For a As Int32 = ListBox1.SelectedItems.Count - 1 To 0 Step -1
For i As Int32 = ListBox1.Items.Count - 1 To 0 Step -1
'-- compare the value of the select item to any given item in the list.
If ListBox1.SelectedItems(a) = ListBox1.Items(i) Then
'-- remove the item by the index we found
ListBox1.Items.RemoveAt(i)
'-- exit the inner for loop
Exit For
End If
Next
Next
End Sub
Private Sub cmdClear_Click(sender As Object, e As EventArgs) Handles cmdClear.Click
ListBox1.Items.Clear()
End Sub
Private Sub HelpToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles HelpToolStripMenuItem.Click
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim lines = DirectCast(e.Argument, String())
Dim Ping As New Ping
Dim replies As New List(Of PingReply)
For Each ip In lines
Dim reply = Ping.Send(ip)
replies.Add(reply)
Next
e.Result = replies
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Dim sb As New System.Text.StringBuilder
Dim replies = DirectCast(e.Result, List(Of PingReply))
For Each reply In replies
Dim index As Integer
index += 1
sb.Append("Ping ").Append(index).Append(": ").Append(reply.Address).Append(" ").Append(reply.RoundtripTime).Append(" ms")
sb.AppendLine()
Next
TextBox1.Text = sb.ToString
End Sub
End Class
Your error is here
one of your ping fails and results an exception which is returned to the completed event handler and when the handler tries to get the result the TargetInvocationException exception is thrown
solution is to check the error
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Error Is Nothing Then
Dim sb As New System.Text.StringBuilder
Dim replies = DirectCast(e.Result, List(Of PingReply))
For Each reply In replies
Dim index As Integer
index += 1
sb.Append("Ping ").Append(index).Append(": ").Append(reply.Address).Append(" ").Append(reply.RoundtripTime).Append(" ms")
sb.AppendLine()
Next
TextBox1.Text = sb.ToString
Else
'error handling
End If
End Sub
additionally you may need to handle the actual error to protect rest of the ping replies otherwise because of 1 failure whole batch of result will be lost
For Each ip As String In lines
Try
Dim reply As PingReply = Ping.Send(ip)
replies.Add(reply)
Catch ex as PingException
'error handling
End Try
Next
Update
another point of error,
For l_index As Integer = 0 To ListBox1.Items.Count - 1
Dim lines As String = CStr(ListBox1.Items(l_index))
BackgroundWorker1.RunWorkerAsync(lines)
Next
since you are passing as single string from the method above and in the method below you are attempting to cast as string array so it fails, change it like this
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim ip = DirectCast(e.Argument, String)
Dim Ping As New Ping
Dim replies As New List(Of PingReply)
Try
Dim reply As PingReply = Ping.Send(ip)
replies.Add(reply)
Catch ex as PingException
'error handling
End Try
e.Result = replies
End Sub
also advised to use Option Strict On to reduce some type checking errors
Thanks!Got it to work! Sending "Listbox1" to array
Private Sub Go_Click(sender As Object, e As EventArgs) Handles Go.Click
Dim lines() As String = ListBox1.Items.OfType(Of String)().ToArray()
BackgroundWorker1.RunWorkerAsync(lines)
End Sub
Now it works app does not crash.
Related
When I click the Button1 the MsgBox shows me "1" which is good.
Private Sub Button1_Click(sender As Object, e As RoutedEventArgs) Handles Button1.Click
MsgBox(CType(sender, Button).Name.Replace("Button", ""))
End Sub
I want the MsgBox shows me "30" when I click the Button2.
Private Sub Button2_Click(sender As Object, e As RoutedEventArgs) Handles Button2.Click
Hello30()
End Sub
Sub Hello30()
'The following line is need to be repaired.
MsgBox(CType(sender, ????).Name.Replace("Hello", ""))
End Sub
Not really sure what you're trying to do, but this is an example that'll get you close:
Imports System.Reflection
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Hello30()
End Sub
Sub Hello30()
Dim method As String = MethodBase.GetCurrentMethod.Name
MsgBox(method.Replace("Hello", ""))
End Sub
Im trying to do a login system where I store the credentials and a desired profile pic image on an access database. the desired result is that when the login matches form 1 closes and opens form 2 with the saved image loaded on a corner.
i tried doing this
Form 1 code:
Imports System.Data.OleDb
Imports System.IO
Public Class Form1
Private PictureFormat As String
Private Sub FillPictureBoxFromFile()
With OpenFileDialog1
.Filter = "(*.jpg)|*.jpg|(*.png)|*.png"
.RestoreDirectory = True
.Title = "Select a file to open"
If .ShowDialog = DialogResult.OK Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
PictureFormat = Path.GetExtension(OpenFileDialog1.FileName)
End With
End Sub
Private cnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\Login Fase 3 Final\Login Fase 3 Final\bin\Release\DBLoginPic.mdb"
Private Sub saveimage()
Dim arrimage() As Byte
Using mstream As New System.IO.MemoryStream
If PictureFormat.ToLower = ".png" Then
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Png)
ElseIf PictureFormat.ToLower = ".jpg" Then
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
End If
arrimage = mstream.GetBuffer()
Dim Filesize As Long
Filesize = mstream.Length
End Using
Using con As New OleDbConnection(cnStr),
cmd As New OleDbCommand("Insert into TBLoginPic (Imagen) Values (#Imagen)", con)
With cmd
.Parameters.Add("#Imagen", OleDbType.Binary).Value = arrimage
'.Parameters.Add("#Nombre", OleDbType.VarChar).Value = TextBox1.Text
con.Open()
.ExecuteNonQuery()
End With
End Using
End Sub
Private Function GetDataByName(name As String) As DataTable
Dim dt As New DataTable
Using conn As New OleDb.OleDbConnection(cnStr),
cmd As New OleDbCommand("Select * from TBLoginPic where Usuario= #Buscar", conn)
cmd.Parameters.Add("#Buscar", OleDbType.VarChar).Value = TBusuario.Text
conn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
End Sub
Private Sub TBusuario_TextChanged(sender As Object, e As EventArgs) Handles TBusuario.TextChanged
End Sub
Private Sub TBcontraseña_TextChanged(sender As Object, e As EventArgs) Handles TBcontraseña.TextChanged
End Sub
Private Sub BtnLoguearse_Click(sender As Object, e As EventArgs) Handles BtnLoguearse.Click
If Me.TBLoginPicTableAdapter.BuscarDatos(Me.DBLoginPicDataSet.TBLoginPic, TBusuario.Text, TBcontraseña.Text) Then
Dim dt As DataTable
Try
dt = GetDataByName(TBusuario.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
TBusuario.Text = dt(0)("Usuario").ToString
Dim arrimage = DirectCast(dt(0)("Imagen"), Byte())
Dim mstream As New System.IO.MemoryStream(arrimage)
PictureBox1.Image = Image.FromStream(mstream)
Form2.Show()
_selectedImage = PictureBox1.Image
Me.Close()
Else
MsgBox("Datos Erroneos")
End If
End Sub
Private Sub BtnRegistrarse_Click(sender As Object, e As EventArgs) Handles BtnRegistrarse.Click
Me.TBLoginPicBindingSource.AddNew()
Me.TBLoginPicBindingSource.EndEdit()
Me.TBLoginPicTableAdapter.Update(Me.DBLoginPicDataSet)
Try
saveimage()
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
MsgBox("Image has been saved in the database")
End Sub
Private Sub BtnExaminar_Click(sender As Object, e As EventArgs) Handles BtnExaminar.Click
FillPictureBoxFromFile()
End Sub
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DBLoginPicDataSet.TBLoginPic' table. You can move, or remove it, as needed.
Me.TBLoginPicTableAdapter.Fill(Me.DBLoginPicDataSet.TBLoginPic)
End Sub
Private Sub TBLoginPicBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
Me.Validate()
Me.TBLoginPicBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DBLoginPicDataSet)
End Sub
End Class
Form 2 Code:
Module imagen
Public _selectedImage As Image
Public ReadOnly Property SelectedImage As Image
Get
Return _selectedImage
End Get
End Property
End Module
Public Class Form2
Private Sub TBLoginPicBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs)
Me.Validate()
Me.TBLoginPicBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DBLoginPicDataSet)
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DBLoginPicDataSet.TBLoginPic' table. You can move, or remove it, as needed.
Me.TBLoginPicTableAdapter.Fill(Me.DBLoginPicDataSet.TBLoginPic)
_selectedImage = PBPerfil.Image
End Sub
Public Sub PBPerfil_Click(sender As Object, e As EventArgs) Handles PBPerfil.Click
End Sub
End Class
and get this error
System.InvalidCastException: 'Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.'
This is how form 1 looks like
This is how form 2 looks like
This is how my database looks like (don't worry there is not any personal info here))
This is where I try to send it from form 1 to 2
This is how I'm trying to receive it on form 2
any tips on what I could do better?
You need to check for nulls. If there is no data in the image column it will error when you try to manipulate it. I would suggest that you selected a default image to display if none is present in the database.
If dt(0)("Usuario") IsNot Nothing OrElse Not IsDBNull(dt(0)("Usuario")) Then
TBusuario.Text = dt(0)("Usuario").ToString
Dim arrimage = DirectCast(dt(0)("Imagen"), Byte())
Dim mstream As New System.IO.MemoryStream(arrimage)
PictureBox1.Image = Image.FromStream(mstream)
Else
PictureBox1.Image = Image.FromFile("DefaultImage.png")
End If
I am basically trying to create an array to export checked items onto a word document. But I am getting an error saying
"Object reference not set to an instance of object."
and
"Referenced 'SelectedMutualFunds' has a value of 'Nothing'
Below is my code:
Public Class ExportFunds
Public SelectedMutualFunds() As String
Private Sub ExportFundOkButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExportFundOkButton.Click
Dim i As Integer
Dim array_Counter As Integer
array_Counter = 0
For i = 0 To ExportFundCheckedListBox.Items.Count() - 1
If ExportFundCheckedListBox.GetItemCheckState(i) = CheckState.Checked Then
SelectedMutualFunds(array_Counter) = ExportFundCheckedListBox.Items(i).ToString
array_Counter += 1
End If
Next
Me.Close()
End Sub
Can someone please help me solve this issue?
You need to provide length to your string array
Public SelectedMutualFunds() As String
to the following within ExportFundOkButton_Click before you use, preferably just before the for loop.
Redim SelectedMutualFunds(ExportFundCheckedListBox.Items.Count() - 1)
You can get this down to a one-liner and fix the NullReference exception at the same time:
Private Sub ExportFundOkButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExportFundOkButton.Click
SelectedMutualFunds = ExportFundCheckedListBox.Items.Where(Function(i) i.CheckState = CheckState.Checked).Select(Function(i) i.ToString()).ToArray()
Me.Close()
End Sub
Or, slightly longer but easier to read:
Private Sub ExportFundOkButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExportFundOkButton.Click
SelectedMutualFunds = ExportFundCheckedListBox.Items.
Where(Function(i) i.CheckState = CheckState.Checked).
Select(Function(i) i.ToString()).
ToArray()
Me.Close()
End Sub
I have a problem.
I am getting this error:
Overload resolution failed because no accessible 'new' can be called
without a narrowing conversion.
Private Sub bt_hapus_Click(sender As Object, e As EventArgs) Handles bt_hapus.Click
Try
Dim sqlda As New SqlClient.SqlDataAdapter("Delete from tblpasien where No_Rkm_Mds=" & Me.No_Rkm_MdsTextBox.Text, Me.KlinikGigiDataSet)
sqlda.Fill(dbpasien, "tblpasien")
MsgBox("Data telah berhasil dihapus")
bersih()
pasif()
normal()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
All source code :
Public Class frm_pasien
Dim dbpasien As New DataSet
Dim dvpasien As New DataView
Dim tekan As Integer
Dim cari As Integer
Private Sub TblpasienBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TblpasienBindingNavigatorSaveItem.Click
Me.Validate()
Me.TblpasienBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.KlinikGigiDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'KlinikGigiDataSet.tblpembayaran' table. You can move, or remove it, as needed.
Me.TblpembayaranTableAdapter.Fill(Me.KlinikGigiDataSet.tblpembayaran)
'TODO: This line of code loads data into the 'KlinikGigiDataSet.tblpasien' table. You can move, or remove it, as needed.
Me.TblpasienTableAdapter.Fill(Me.KlinikGigiDataSet.tblpasien)
End Sub
Private Sub BindingNavigatorDeleteItem_Click(sender As Object, e As EventArgs) Handles BindingNavigatorDeleteItem.Click
End Sub
Private Sub BindingNavigatorAddNewItem_Click(sender As Object, e As EventArgs) Handles BindingNavigatorAddNewItem.Click
End Sub
Private Sub bt_keluar_Click(sender As Object, e As EventArgs) Handles bt_keluar.Click
Dim pesan As DialogResult = MsgBox("Apakah anda yakin akan keluar", MsgBoxStyle.OkCancel)
If pesan = DialogResult.OK Then
Me.Close()
Else
Exit Sub
End If
End Sub
Private Sub bt_hapus_Click(sender As Object, e As EventArgs) Handles bt_hapus.Click
Try
Dim sqlda As New SqlClient.SqlDataAdapter("Delete from tblpasien where No_Rkm_Mds=" & Me.No_Rkm_MdsTextBox.Text, Me.KlinikGigiDataSet)
sqlda.Fill(dbpasien, "tblpasien")
MsgBox("Data telah berhasil dihapus")
bersih()
pasif()
normal()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub bersih()
Me.No_Rkm_MdsTextBox.Clear()
Me.NamaTextBox.Clear()
Me.UmurTextBox.Clear()
Me.Tgl_LhrTextBox.Clear()
Me.AlamatTextBox.Clear()
Me.No_HpTextBox.Clear()
Me.No_Rkm_MdsTextBox.Focus()
End Sub
Private Sub pasif()
Me.No_Rkm_MdsTextBox.Enabled = False
Me.NamaTextBox.Enabled = False
Me.UmurTextBox.Enabled = False
Me.Tgl_LhrTextBox.Enabled = False
Me.AlamatTextBox.Enabled = False
Me.No_HpTextBox.Enabled = False
End Sub
Private Sub normal()
Me.bt_tambah.Enabled = True
Me.bt_edit.Enabled = True
Me.bt_simpan.Enabled = False
Me.bt_reset.Enabled = False
Me.bt_hapus.Enabled = False
Me.bt_keluar.Enabled = True
End Sub
Private Sub binding()
Me.No_Rkm_MdsTextBox.DataBindings.Clear()
Me.No_Rkm_MdsTextBox.DataBindings.Add("Text", dvpasien, "Id")
Me.NamaTextBox.DataBindings.Clear()
Me.NamaTextBox.DataBindings.Add("Text", dvpasien, "Nama")
Me.UmurTextBox.DataBindings.Clear()
Me.UmurTextBox.DataBindings.Add("Text", dvpasien, "Alamat")
Me.Tgl_LhrTextBox.DataBindings.Clear()
Me.Tgl_LhrTextBox.DataBindings.Add("Text", dvpasien, "Ttl")
Me.AlamatTextBox.DataBindings.Clear()
Me.AlamatTextBox.DataBindings.Add("value", dvpasien, "Jkl")
Me.No_HpTextBox.DataBindings.Clear()
Me.No_HpTextBox.DataBindings.Add("Text", dvpasien, "Pekerjaan")
End Sub
Private Sub No_Rkm_MdsTextBox_TextChanged(sender As Object, e As EventArgs) Handles No_Rkm_MdsTextBox.TextChanged
If Len(Me.No_Rkm_MdsTextBox.Text) < 10 Then
Exit Sub
End If
dvpasien.Sort = "Id"
Try
cari = dvpasien.Find(Me.No_Rkm_MdsTextBox.Text)
If cari = -1 Then
If tekan = 1 Then
Me.No_Rkm_MdsTextBox.Focus()
Else
MsgBox("Data tidak ada")
bersih()
End If
Else
If tekan = 1 Then
MsgBox("Data sudah ada")
bersih()
Else
binding()
tampilgrid()
Me.bt_edit.PerformClick()
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub tampilgrid()
Throw New NotImplementedException
End Sub
End Class
Please help this is my essay from my lecturer.
Have you declared your dataset with New keyword?
Means something as follows:
Dim dbpasien As New DataSet()
Or
Using dbpasien As DataSet = New DataSet()
MSDN explains this exception is due to bad overloaded method types
You have made a call to an overloaded method, but the compiler cannot find a method that can be called without a narrowing conversion. A narrowing conversion changes a value to a data type that might not be able to precisely hold some of the possible values.
I wrote the following code:
Public Class Form1
Private Structure udtThing
Dim SomeText As String
Dim SomeElements() As String
Public Shared Function CreateInstance() As udtThing
Dim result As New udtThing
result.SomeText = String.Empty
ReDim result.SomeElements(2)
result.SomeElements(0) = String.Empty
result.SomeElements(1) = String.Empty
result.SomeElements(2) = String.Empty
Return result
End Function
End Structure
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim nThings() As udtThing
nThings = Array.CreateInstance(GetType(udtThing), 10)
End Sub
End Class
I partly works, nThings becomes an array of 11 udtThings.
But .SomeElements is not redimmed to 3 strings of String.Empty, but it is "Nothing" instead.
Does anybody see where I went wrong?
Thank you very much!
By design, a Redim is required. Array.CreateInstance() isn't going to perform that operation, it can't guess what size is required. You'll have to help:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim nThings(10) As udtThing
For ix As Integer = 0 To UBound(nThings)
nThings(ix) = udtThing.CreateInstance()
Next
End Sub