Null Reference Exception Run Time Error - vb.net

Hi all im getting a null reference run time error with one line of code in my project, however if i break point it and then step through it everything works fine. Any Thoughts
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim checkbox_l As String = "CheckBox"
Dim checkbox_i As string
For i As Integer = 1 To id Step 1
checkbox_i = checkbox_l + i.ToString
Try
If CType(Panel1.Controls(checkbox_i), CheckBox).Checked = True Then
My.Settings.name = Panel1.Controls("CheckBox" & i).Text
Call installer_properties()
Call start_install()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Next
End Sub
The code is meant to check if a dynamically created checkbox has been checked and then move on accordingly, however im getting an error with the line
If CType(Panel1.Controls(checkbox_i), CheckBox).Checked = True Then

Use Debug.Assert to catch it
Dim c as Control = Panel1.Controls(checkbox_i)
Debug.Assert(c IsNot Nothing)
Dim cb as CheckBox = TryCast(c, CheckBox)
If cb isNot Nothing Then
If cb.Checked = True Then
My.Settings.name = cb.Text
Call installer_properties()
Call start_install()
End If
End If

To get result 1 if checked and 0 - if not, you can write down:
textbox1.text = Microsoft.VisualBasic.Right(Panel1.Controls("CheckBox" & i).ToString, 1)

Related

Threading doesn't complete the task before ending the thread loop

So I did something similar a while ago, but this is essentially a username checker for a (specific) website, they can load in usernames via text file and it will put it into a list box, now I have the start button and it's meant to check each username. Before, however, it froze the program when they checked, but it worked. I tried making it "threaded" so it didn't freeze.
The problem now is that it doesn't check them all, and finishes instantly.
CODE:
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Button6.Enabled = False
Dim goodUsers As New SaveFileDialog()
goodUsers.Filter = "TXT file (*.txt)|*.txt"
Dim flag As Boolean
Dim Incomplete As Integer = 0
Dim Taken As Integer = 0
Dim sb As New StringBuilder
If goodUsers.ShowDialog() = DialogResult.OK Then
Dim checkerMT As New Thread(
Sub()
For Each i As String In UsernameList.Items
WebRequest.Create("http://yatobooter.cf/other/checkusr.php?username=" + i.ToString)
Dim cResult As String = New System.Net.WebClient().DownloadString("http://yatobooter.cf/other/checkusr.php?username=" + i.ToString).ToString
If cResult = "taken" Then
flag = False
ElseIf cResult = "nottaken" Then
flag = True
End If
If flag = True Then
sb.Append(i & vbNewLine)
Else
Incomplete = Incomplete + 1
Taken = UsernameList.Items.Count - Incomplete
End If
Next
End Sub
)
checkerMT.Start()
Try
File.WriteAllText(goodUsers.FileName, sb.ToString)
Catch ex As Exception
Exit Sub
End Try
End If
MessageBox.Show("Checking available usernames, complete!", "NameSniper Pro")
Button6.Enabled = True
End Sub
You cannot access UI elements (UsernameList.Items) from a thread other than the UI. Instead add a background worker to your form to handle the basic threading stuff (progress reporting, finish reporting, exception handling). Pass into this an object that contains the settings your job needs to do its work without interacting with the ui.
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Button6.Enabled = False
Dim goodUsers As New SaveFileDialog()
goodUsers.Filter = "TXT file (*.txt)|*.txt"
If goodUsers.ShowDialog() = DialogResult.OK Then
'Note: You'll need to add the filenames
BackgroundWorker1.RunWorkerAsync(New State() With {.Names = {}, .FileName = goodUsers.FileName})
End If
End Sub
Class State
Public Names As List(Of String)
Public StringBuilder As New System.Text.StringBuilder
Public Incomplete As Integer
Public Taken As Integer
Public FileName As String
End Class
Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim state = CType(e.Argument, State)
For Each i As String In state.Names
Using cli = New System.Net.WebClient()
Dim cResult = cli.DownloadString("http://yatobooter.cf/other/checkusr.php?username=" + i.ToString).ToString
If cResult = "nottaken" Then
state.StringBuilder.Append(i & vbNewLine)
Else
state.Incomplete = state.Incomplete + 1
state.Taken = state.Names.Count - state.Incomplete
End If
End Using
Next
IO.File.WriteAllText(state.FileName, state.StringBuilder.ToString)
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Error IsNot Nothing Then
MessageBox.Show(e.Error.ToString(), "Error")
Else
MessageBox.Show("Checking available usernames, complete!", "NameSniper Pro")
End If
Button6.Enabled = True
End Sub
The SaveFileDialog can be used as "Using directive"
Why do you create a webrequest on the one hand, and on the other hand use a webclient? That does not make sense at all.
Instead of your strange if condition, write:
flag = (cResult.Equals("nottaken"))
All code you want to run after the actions you are currently running in your thread have to be in your thread as well, because it is async.
You have to invoke if you use user controls within a thread
and so on..
Please turn Option Strict On and Option Infer Off
There are lots of other things you could do better.
Please remove the webrequest and webclient combination yourself, that does not make sense at all.
Take a look at this, I cleared it a little bit:
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim Incomplete As Integer = 0
Dim Taken As Integer = 0
Dim sb As New StringBuilder
Using goodUsers As SaveFileDialog = new SaveFileDialog()
goodUsers.Filter = "TXT file (*.txt)|*.txt"
If not goodUsers.ShowDialog() = DialogResult.OK Then Exit Sub
Dim checkerMT As New Thread(
Sub()
Me.invoke(sub()
Button6.Enabled = False
For Each i As String In UsernameList.Items
WebRequest.Create("http://yatobooter.cf/other/checkusr.php?username=" + i.ToString)
Dim cResult As String = New System.Net.WebClient().DownloadString("http://yatobooter.cf/other/checkusr.php?username=" + i.ToString).ToString
If (cResult.toLower().Equals("nottaken")) Then
sb.Append(String.Concat(i , Environment.NewLine)
Else
Incomplete += 1
Taken = UsernameList.Items.Count - Incomplete
End If
Next
File.WriteAllText(goodUsers.FileName, sb.ToString)
Button6.Enabled = True
MessageBox.Show("Checking available usernames, complete!", "NameSniper Pro")
End Sub)
End Sub
)
checkerMT.IsBackground = True;
checkerMT.Start()
End Sub

ERROR with a basic user interaction program in VB.NET

Can some please advise me of what I'm doing wrong.
I'm new to visual basic 2012
What I am trying to do:
One input is saved into an Integer variable. The other input is saved into a Byte variable.
The output is calculated as the Integer * Byte/100 to the power 2.
If the user enters a non-numeric value, and clicks the button, show an error of "Illegal Value entered" using Messagebox.
If the user enters an "out of range" number, show an error of "input not in valid range" using Messagebox.
This is the code that I have:
Public Class Form1
Dim T1 As String
Dim T2 As String
Dim a As Integer
Dim b As Byte
Dim c As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
TextBox1.Text = False
TextBox2.Text = False
a = CInt(TextBox1.Text)
b = CByte(TextBox2.Text)
c = a * b / 100
c = c * a * b / 100 ^ 2
Label3.Text = "Output:" + c.ToString()
Catch ex As ArgumentOutOfRangeException
MessageBox.Show("Illegal Value Entered")
Catch ex As IndexOutOfRangeException
MessageBox.Show("Input not in valid range")
Catch ex As Exception
MessageBox.Show("Some exception has occured")
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Close()
End Sub
End Class
Please remove the expressions TextBox1.Text = False (and for TextBox2) this would always force CInt() and CByte() to parse a string 'False' (not a user provided number). Your code should look like this.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
a = CInt(TextBox1.Text)
b = CByte(TextBox2.Text)
c = a * b / 100
c = c * a * b / 100 ^ 2
Label3.Text = "Output:" + c.ToString()
Catch ex As ArgumentOutOfRangeException
MessageBox.Show("Illegal Value Entered")
Catch ex As IndexOutOfRangeException
MessageBox.Show("Input not in valid range")
Catch ex As Exception
MessageBox.Show("Some exception has occured")
End Try
End Sub
If you want to clear the numbers from textboxes after calculation, then please put these lines of code right after Label3.Text = ... line
TextBox1.Text = False
TextBox2.Text = False
CByte documentation clearly states that
If expression lies outside the acceptable range for the byte subtype,
an error occurs.
CByte(...) constructor would not be able to parse any number greater than 255.

VB Control after click event completes

I'm having a problem with a click-event that deletes a series of controls. In stepping though the click event, everything works perfectly but other text box controls on the page are being blanked out (not deleted, just losing their text content). I've stepped through the code and found that everything is find going into the "End Sub" statement of the click event but the blanking out happens when the End Sub is executed. I'm attaching the click event but there's not much to see. Any ideas what's happening?
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
CommonDelete(tbline.Text)
End Sub
Public Sub CommonDelete(LineNum As Integer)
Dim i As Integer = 0
Dim j As Integer = 0
Dim lineFound As Boolean = False
Dim LineInt As Integer = 0
Dim VLength As String = " "
Dim VLengthInt As Integer = 0
topLine = 0
bottomLine = 0
VLength = arrTextVals.GetLength(1)
VLengthInt = CInt(VLength)
Try
LineInt = CInt(LineNum)
Catch ex As Exception
MessageBox.Show("The line you selected is invalid", "Drop Zone Error DL1:",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1)
Exit Sub
End Try
For i = 1 To VLengthInt - 1
If arrTextVals(1, i) = LineNum Then
lineFound = True
Exit For
End If
Next
If lineFound <> True Then
MessageBox.Show("The line you selected is invalid", "Drop Zone Error DL2:",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1)
Exit Sub
End If
For j = i To VLengthInt - 2
topLine = j
bottomLine = j + 1
SwitchRows()
Next
RemoveControl(arrTextVals(0, bottomLine))
RemoveControl(arrTextVals(2, bottomLine))
RemoveControl(arrTextVals(4, bottomLine))
RemoveControl(arrTextVals(6, bottomLine))
tbline.Text = " "
End Sub
Private Sub RemoveControl(ControlName As String)
Dim ctr As Control
For Each ctr In Me.Controls
If ctr.Name = ControlName Then
Me.Controls.Remove(ctr)
Exit Sub
End If
Next ctr
End Sub

For Loop works not working, or giving error. Works when conditions are reversed

I don't know if its the late hour, but I am working on the following array For Loop:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim pboxes() As PictureBox = {picMainImage, picImage2, picImage3, picImage4}
For i As Integer = 0 To pboxes.Count - 1
If pboxes(i).Image Is My.Resources.list Then
pboxes(i).Image = Nothing
End If
Next
End Sub
The loop is supposed to check if any of the picture boxes in the array have an Image called List stored on the Resources folder in them. If it does, set the image to Nothing. However, I run it and nothing happens., no errors, nothing.
So I reversed my For Loop as follows to see what happens:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim pboxes() As PictureBox = {picMainImage, picImage2, picImage3, picImage4}
For i As Integer = 0 To pboxes.Count - 1
If pboxes(i).Image Is Nothing Then
pboxes(i).Image = My.Resources.list
End If
Next
End Sub
This works but is not what I want, I want the opposite.
What am I doing wrong here?
One option is if you set the pictures in the box programatically, set My.Resources.list to be referenced by a global variable, ie Public pbList = My.Resources.list
Then, when you set the picture initially, use that variable, so: picMainImage.Image = pbList
Finally, in your If statement, you should then be able to check If pboxes(i) is pbList Then...
Once it becomes a variable, it seems to become static and therefore wherever you use it, it will always be the same.
EDIT: some actual code that I used a few months back:
In the module (outside sub)
Public pbimage As System.Drawing.Image = My.Resources.placeholder
Then in the Sub
If imgpath <> "" Then
Me.lblImg.ImageLocation = imgpath
Else
Me.lblImg.ImageLocation = Nothing
Me.lblImg.Image = pbimage
End If
and then this is what I use for all pictures without issues (its a function that I have run when you click on an image - if its the placeholder then you can browse for an image and save it to a data folder, otherwise it does nothing)
Private Sub changeImg(sender As Object, e As MouseEventArgs) Handles {ALL YOUR IMAGES}.Click
If TypeOf sender Is PictureBox Then
If DirectCast(sender, PictureBox).Image Is pbimage Then
Dim ofd As New OpenFileDialog
ofd.Title = "Please select image"
ofd.Filter = "Image Files|*.jpg"
If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim rn As New Random
Dim r As Long = rn.Next(111111, 999999)
Dim newfilename As String = My.Settings.dataPath & r.ToString & Format(Now, "ddmmyy") & ".jpg"
Try
FileCopy(ofd.FileName, newfilename)
DirectCast(sender, PictureBox).ImageLocation = newfilename
Catch ex As Exception
MessageBox.Show("Check permissions to the Data folder", "Permissions error")
End Try
End If
End If
End If
End Sub
Images cannot be compared that way because the image is copied into memory and will always be different even if the pixels match. Compare the pixels directly to find out if the image is the same.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim pboxes() As PictureBox = {picMainImage, picImage2, picImage3, picImage4}
For i As Integer = 0 To pboxes.Count - 1
If IsSameImage(pboxes(i).Image, My.Resources.list) = True Then
pboxes(i).Image = Nothing
End If
Next
End Sub
Public Function IsSameImage(ByVal oBitmap1 As Bitmap, ByVal oBitmap2 As Bitmap) As Boolean
For x = 0 To oBitmap1.Width - 1
For y = 0 To oBitmap2.Height - 1
If Not oBitmap1.GetPixel(x, y) = oBitmap2.GetPixel(x, y) Then
Return False
End If
Next
Next
Return True
End Function

VB.Net Data Grid View

I am getting problems with my code. It's saying in the error that I should put a New in the code but i don't know where to put it. This is the complete code for the function:
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Try
Dim TA As New POSCanteenTableAdapters.ItemsTableAdapter
Dim TB = TA.GetDataByBarcode(TextBox1.Text)
If TB.Rows.Count = 0 Then
TextBox2.Text = ""
TextBox3.Text = ""
Button1.Enabled = False
Exit Sub
End If
Button1.Enabled = True
Dim IR As POSCanteen.ItemsRow = TB.Rows(0)
TextBox2.Text = IR.ItemName
TextBox3.Text = IR.SellPrice
Button2.Tag = IR
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IR As POSCanteen.ItemsRow = Button1.Tag
Dim RI As New Integer
Dim ItemLoc As Integer = -1
For RI = 0 To CDGV3.Rows.Count - 1
If IR.Barcode = CDGV3.Rows(RI).Cells(0).Value Then
ItemLoc = RI
Exit For
End If
Next
If ItemLoc = -1 Then
CDGV3.Rows.Add(IR.Barcode, IR.ItemName, IR.BuyPrice, IR.SellPrice, 1, IR.SellPrice)
Else
Dim ItemCount As Long = CDGV3.Rows(ItemLoc).Cells(4).Value
ItemCount += 1
Dim NewPrice As Decimal = IR.SellPrice * ItemCount
CDGV3.Rows(ItemLoc).Cells(4).Value = ItemCount
CDGV3.Rows(ItemLoc).Cells(5).Value = NewPrice
End If
TextBox1.Text = ""
TextBox1.Focus()
End Sub
It is supposed to add an item in the Data Grid but it won't because of that error. I don't know where to put it since the compiler doesn't tell me where.
This is the exception message: Object reference not set to an instance of an object.
You need to think ahead for the possibility that an object does not convert(esp when you let the compiler guess). Not sure if that is the object causing the problem, but you may know. Learn how to step through the code with the debugger.
Dim IR = TryCast(Button1.Tag, {type})
If Not IR Is Nothing Then
'rest of your code
End If
I can't get your line so i'm suggesting this.
Try any of this
Dim IR As New POSCanteen.ItemsRow = Button1.Tag
Dim ItemCount As New Long = CDGV3.Rows(ItemLoc).Cells(4).Value
Dim NewPrice As New Decimal = IR.SellPrice * ItemCount