Object reference not set to an instance of an object. ListViewItem VB.NET - vb.net-2010

Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
Dim myList As ListViewItem
Dim JmlList As Integer
Dim i As Integer
JmlList = lst_detail.Items.Count - 1
i = 0
myList = lst_detail.Items.Add(str(lst_detail.Items.Count + 1)) // error at this
myList.SubItems.Add(txtKodeObat.Text.Trim)
myList.SubItems.Add(txtNamaObat.Text.Trim)
myList.SubItems.Add(txtHarga.Text.Trim)
myList.SubItems.Add(txtQty.Text.Trim)
myList.SubItems.Add(txtJumlah.Text.Trim)
Dim subtotal As Double = 0
JmlList = lst_detail.Items.Count - 1
For i = 0 To JmlList
subtotal = subtotal + Val(lst_detail.Items(i).SubItems(5).Text)
Next
txtSubTotal.Text = Format(subtotal, "##########")
txtPPn.Text = Format(subtotal * 0.1, "##########")
txtTotal.Text = Val(txtSubTotal.Text) + Val(txtPPn.Text)
txtKodeObat.Text = ""
txtNamaObat.Text = ""
txtHarga.Text = "0"
txtQty.Text = ""
txtJumlah.Text = "0"
txtKodeObat.Focus()
End Sub
I got error at myList = lst_detail.Items.Add(str(lst_detail.Items.Count + 1))
i want to add from text to listitem but got null error
i have fill that textbox

lst_detail or lst_detail.Items seems to be null. Debug the code and you should be able see one of these null. If lst_detail is null and you are trying to access lst_detail.Items it will throw "Null reference" execption - which means you are trying to access something from a object with null value.

It looks like you're trying to pull data from a specific index within the lst_detail. I didn't test the following code, but something like the following might do what you're trying to do.
myList = lst_detail.Items.Add(lst_detail.Items[lst_detail.Items.Count + 1].ToString())

Related

If I click the calculate button the program crashes?

Just for context;
I need to calculate the average of 5 numbers located in 5 textboxes.
Nummer means number
Gemiddelde means average
and
Bereken means calculate
What is causing it to crash?
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click
'Variabelen'
Dim nummer1 As Decimal = txtNummer1.Text
Dim nummer2 As Decimal = txtNummer2.Text
Dim nummer3 As Decimal = txtNummer3.Text
Dim nummer4 As Decimal = txtNummer4.Text
Dim nummer5 As Decimal = txtNummer5.Text
Dim somNummers As Decimal = nummer1 + nummer2 + nummer3 + nummer4 + nummer5
Dim Gemiddelde As String = (somNummers) / 5
lblGemiddelde.Text = Gemiddelde
If Gemiddelde < 5.5 Then
lblGemiddelde.Text = Gemiddelde + " Dit is onvoldoende"
End If
If nummer1 = "" Or nummer2 = "" Or nummer3 = "" Or
nummer4 = "" Or nummer5 = "" Then
butBereken.Enabled = False
MessageBox.Show("your mom")
Else
butBereken.Enabled = True
End If
End Sub
I don't see what would crash the program but check to that the TextBoxes have values before assigning them to numeric variables. A Decimal value will never = "".
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click 'Variabelen'
If Not IsNumeric(txtNummer1.Text) Or _
Not IsNumeric(txtNummer2.Text) Or _
Not IsNumeric(txtNummer3.Text) Or _
Not IsNumeric(txtNummer4.Text) Or _
Not IsNumeric(txtNummer5.Text) Then
MessageBox.Show ("your mom wants you to fill in all the number boxes")
Exit Sub
End If
Dim nummer1 As Decimal = CDec(txtNummer1.Text)
Dim nummer2 As Decimal = CDec(txtNummer2.Text)
Dim nummer3 As Decimal = CDec(txtNummer3.Text)
Dim nummer4 As Decimal = CDec(txtNummer4.Text)
Dim nummer5 As Decimal = CDec(txtNummer5.Text)
Dim somNummers As Decimal = nummer1 + nummer2 + nummer3 + nummer4 + nummer5
Dim Gemiddelde As String = (somNummers) / 5
lblGemiddelde.Text = Gemiddelde
If Gemiddelde < 5.5 Then
lblGemiddelde.Text = Gemiddelde + "Dit is onvoldoende"
End If
If nummer1 = 0 Or nummer2 = 0 Or nummer3 = 0 Or nummer4 = 0 Or nummer5 = 0 Then
butBereken.Enabled = False
MessageBox.Show ("your mom")
Else
butBereken.Enabled = True
End If
End Sub
If this doesn't work I would consider setting breakpoints in the could to determine what line is causing the crash.
If that doesn't work consider adding this line to the form's initialization:
butBereken.Caption = "Warning: Do not Click!"
Assuming the user populated all the textboxes with numeric only data, (and you have checked this) try replacing these lines in your code with this code
Dim nummer1 As Decimal = txtNummer1.Text
Dim nummer2 As Decimal = txtNummer2.Text
Dim nummer3 As Decimal = txtNummer3.Text
Dim nummer4 As Decimal = txtNummer4.Text
Dim nummer5 As Decimal = txtNummer5.Text
Dim somNummers As Decimal = nummer1 + nummer2 + nummer3 + nummer4 + nummer5
Dim Gemiddelde As Decimal = somNummers / 5
lblGemiddelde.Text = Gemiddelde.ToString("##0.0")
I'd do something more like:
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click
Dim TBs() As TextBox = {txtNummer1, txtNummer2, txtNummer3, txtNummer4, txtNummer5}
Dim inputs() As String = TBs.Select(Function(x) x.Text).ToArray()
Dim values() As Decimal
Try
values = Array.ConvertAll(inputs, Function(s) Decimal.Parse(s))
Dim Gemiddelde As String = values.Average()
lblGemiddelde.Text = Gemiddelde & If(Gemiddelde < 5.5, " Dit is onvoldoende", "")
Catch ex As Exception
MessageBox.Show("your mom")
End Try
End Sub
I prefer this approach as it doesn't require repetitive lines of code, manually converting each TextBox to a Decimal. Since the TextBoxes are in an Array, we could also add another TextBox to the form and then add that name to the end of the Array. The rest of the code would not need to change at all; it would still just work as is.
From the Array of TextBox, we use a LINQ statement to extract the Text from each TextBox and add it to an Array of String called "inputs". From there, we convert every single String to a Decimal using Array.ConvertAll(), again avoiding repetitive code. If any of the input values is not a valid Decimal then an Exception will be thrown and we'll jump the the Catch block where the not so well written error message is displayed.
If there are no exceptions, then all String inputs were successfully converted to Decimals and stored in the "values" Array. Next we simply use the LINQ function Average() to get the average of all the values.
Lastly we display the computed average in the Label, adding the "Dit is onvoldoende" message if approapriate. The If() function used in this line is simply a shorthand version of a longer If...Else...End If statement.
In your original attempt, it looks like you wanted to disable the button if any of the values are blank (or maybe if they are invalid decimals?):
If nummer1 = "" Or nummer2 = "" Or nummer3 = "" Or nummer4 = "" Or nummer5 = "" Then
butBereken.Enabled = False
MessageBox.Show("your mom")
Else
butBereken.Enabled = True
End If
This makes no sense as if you disable the button, how would it get turned back on so that user could click it again?
A different approach would be to handle the TextChanged() event of all the TextBoxes and simply update your Label with the average in real-time whenever one of the TextBoxes is changed:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
UpdateAverage()
End Sub
Private Sub txtAll_TextChanged(sender As Object, e As EventArgs) Handles txtNummer5.TextChanged, txtNummer4.TextChanged, txtNummer3.TextChanged, txtNummer2.TextChanged, txtNummer1.TextChanged
UpdateAverage()
End Sub
Private Sub UpdateAverage()
Dim TBs() As TextBox = {txtNummer1, txtNummer2, txtNummer3, txtNummer4, txtNummer5}
Dim inputs() As String = TBs.Select(Function(x) x.Text).ToArray()
Try
Dim values() As Decimal = Array.ConvertAll(inputs, Function(s) Decimal.Parse(s))
Dim average As Decimal = values.Average
lblGemiddelde.Text = average & If(average < 5.5, " Dit is onvoldoende", "")
Catch ex As Exception
lblGemiddelde.Text = "{ Invalid Input }"
End Try
End Sub
End Class
Sample run:

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

Array copy will not work in a if statement or by button click sub

I am trying to make a small log ( string array of 10 ) of time stamps that on a event will move the newest event towards the first string in the array.
Here is a few attempts that I have tried. The only time the array will change is when it is in a timer.
What Iam looking to do is
on a bit change to copy arrayA(1) to array(0). witch will move the string from (1) to (0),(2) to (1),(3) to (2) and the rest of the array. So when the event happens it cascades the strings to make a list of last events (0) would be the 10th event that happened and the (9) would be the first or latest event
Attempt 1
Private Sub RcvTmr_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RcvTmr.Tick
dim SrvUpTimeStgArray(9) as string
If BtnBit = False And OneShot(5) = True Then
OneShot(5) = False
SrvUpTimeStgArray(9) = LAtimeSvrUp.TimeString
For I = 0 To 8
SrvUpTimeStgArray(I) = SrvUpTimeStgArray(I + 1)
Next
LAtimeSvrUp.StopTimer()
End If
ListBox1.DataSource = SrvUpTimeStgArray
End Sub
Then this code to
Private Sub RcvTmr_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RcvTmr.Tick
Dim StringArrayA(9) as string : Dim StringArrayB(9) as string
If OneShot(10) = False Then
OneShot(10) = True
StringArrayA(3) = "testst 33333"
StringArrayA(2) = "testst 22222"
StringArrayA(1) = "testst 11111"
StringArrayA(0) = "testst 00000"
End If
StringArrayA(0) = StringArrayA(1)
If Btn1TestBit Then
counter1 = counter1 + 1
BtnTest3.Text = "worked"
'Call ArrayCopy()
Btn1TestBit = False
StringArrayA(0) = StringArrayA(1)
' The below was alternated with the above line ans also did not work
' Array.Copy(StringArrayA, 1, StringArrayB, 0, 4)
End If
ListBox1.DataSource = StringArrayA
ListBox2.DataSource = StringArrayB
Lacount3.Text = counter1
End Sub
I am missing something so thanks..
Update but It has duplicate strings to the array
This is using the AddLog Sub
If ClientConnBit = False And OneShot(5) = True Then
OneShot(5) = False
AddLog(SrvUpTimeStgArray, "Stopped # " & DateTime.Now.ToString() & "* Up Time " & LAtimeSvrUp.TimeString)
LAtimeSvrUp.StopTimer()
For Each entry As String In SrvUpTimeStgArray
If Not String.IsNullOrEmpty(entry) Then
LBSvrUptimeLog.Items.Add(entry)
End If
Next
'LBSvrUptimeLog.DataSource = SrvUpTimeStgArray
My.Settings.UpTimeString.AddRange(SrvUpTimeStgArray)
My.Settings.Save()
End If
You need to copy the values backward, if you do it forward you'll end up copying the same value everywhere. I suggest you load how to use break point and watch.
This is how it would look like
Sub AddLog(ByVal logAsArray() As String, ByVal newEntry As String)
For index As Integer = logAsArray.Length - 1 To 1 Step -1
logAsArray(index) = logAsArray(index - 1)
Next
logAsArray(0) = newEntry
End Sub
You can also use list instead
Sub AddLog(ByVal logAsList As List(Of String), ByVal newEntry As String)
If logAsList.Count = logAsList.Capacity Then
logAsList.RemoveAt(logAsList.Capacity - 1)
End If
logAsList.Insert(0, newEntry)
End Sub
Here's an example on how to use these functions.
Sub Main()
Dim logAsArray(2) As String
AddLog(logAsArray, "a")
AddLog(logAsArray, "b")
AddLog(logAsArray, "c")
AddLog(logAsArray, DateTime.Now.ToString())
For Each entry As String In logAsArray
Console.WriteLine(entry)
Next
Dim logAsList As New List(Of String)(3)
AddLog(logAsList, "a")
AddLog(logAsList, "b")
AddLog(logAsList, "c")
AddLog(logAsList, DateTime.Now.ToString())
For Each entry As String In logAsList
Console.WriteLine(entry)
Next
Console.ReadLine()
End Sub

Send text from textboxes to datagrid

I have for textboxes on my form and I would like the text there to be send to a datagrid. I wrote the following:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim itemName As String = txtItem.Text
Dim qty As Double = CDbl(txtQTY.Text)
Dim price As Double = CDbl(txtPrice.Text)
Dim Total As Double = price * qty
txtTotal.Text = Convert.ToString(Total)
Dim row As Integer = grdNewInvoice.Rows.Count
Dim data As TextBox() = New TextBox() {txtItem, txtQTY, txtPrice, txtTotal}
grdNewInvoice.Rows.Add()
For i As Integer = 0 To data.Length - 1
grdNewInvoice(i, row).Value = data(0)
Next
End Sub
But I get the following on my datagrid row: System.Windows.Forms.TextBox, Text: [textbox string]
I tried the following code as well to make sure there was nothing wrong with my settings on my datagrid:
'grdNewInvoice.Rows(0).Cells(0).Value = itemName
'grdNewInvoice.Rows(0).Cells(1).Value = qty
'grdNewInvoice.Rows(0).Cells(2).Value = price
'grdNewInvoice.Rows(0).Cells(3).Value = Total
That worked fine and the text went in as expected but since I will be writing to multiple lines on the datagrid, I will need to use a loop.
What am I doing wrong here?
One way to do this is to use a list of string array.
Dim row As Integer = grdNewInvoice.Rows.Count
Dim data As New List(Of String())
data.Add({txtItem.Text, txtQTY.Text, txtPrice.Text, txtTotal.Text})
data.Add({"Item2", "qtr2", "price2", "total2"})
data.Add({"Item3", "qty3", "price3", "total3"})
For i As Integer = 0 To data.Count - 1
grdNewInvoice.Rows.Add(data(i))
Next

Visual Basic: NullReferenceException was unhandled

I can't work out what's causing it. The error report says "Object variable or With block variable not set." for the line "allSlotLabels(i).Image = imgCherries". This line is no different from the other, so I guess it's just the error it picked up first after randomly generating the number. Any help at all would be appreciated, I'm completely stuck.
Public Class frmSlotMachine
' Declare all variables needed
Dim startingCoins As Integer = 5
Dim coins As Integer = startingCoins + 1
Dim numbersGenerated As Integer = 20
Dim spinStatus As String = "Start"
Dim held1 As Boolean = False
Dim held2 As Boolean = False
Dim held3 As Boolean = False
Dim slot1Name, slot2Name, slot3Name As String
Dim slot1Value, slot2Value, slot3Value As Integer
' Assign resources to variables
Dim imgBanana As Image = My.Resources.banana
Dim imgOrange As Image = My.Resources.orange
Dim imgSeven As Image = My.Resources.seven
Dim imgCherries As Image = My.Resources.cherries
Dim imgBatman As Image = My.Resources.batman
Dim imgCross As Image = My.Resources.cross
' Declare arrays
Dim allHelds() As Boolean = {held1, held2, held3}
Dim allSlotValues() As Integer = {slot1Value, slot2Value, slot3Value}
Dim allSlotNames() As String = {slot1Name, slot2Name, slot3Name}
Dim allSlotLabels() As Object = {lblSlot1, lblSlot2, lblSlot3}
Private Sub btnSpin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSpin.Click
' Trying a for loop to randomise numbers and assign images, if hold is off
For i = 1 To 3
If Not allHelds(i) Then
allSlotValues(i) = Int(Rnd() * numbersGenerated + 0.5)
Select Case allSlotValues(i)
Case 0 To 5
allSlotLabels(i).Image = imgBanana
allSlotNames(i) = "Banana"
Case 6 To 11
allSlotLabels(i).Image = imgOrange
allSlotNames(i) = "Orange"
Case 12 To 16
allSlotLabels(i).Image = imgCherries
allSlotNames(i) = "Cherries"
Case 17 To 19
allSlotLabels(i).Image = imgSeven
allSlotNames(i) = "Seven"
Case 20
allSlotLabels(i).Image = imgBatman
allSlotNames(i) = "Batman"
Case Else
allSlotLabels(i).Text = "Error. Current slot value = " & allSlotValues(i)
End Select
End If
Next
How about: For i = 0 To 2. Indexes start with 0, not with 1.
change the assignment of slots as follows:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
allSlotLabels(0) = lblslot1
allSlotLabels(1) = lblslot2
allSlotLabels(2) = lblslot3
End Sub
and the loop to
For i = 0 To 2