VB.Net Data Grid View - vb.net

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

Related

How to change filepath when check a radiobutton? Visual basic

My problem here is that i have 3 radiobuttons for 3 different categories:
Huse Folii and Altele.
The idea is when i select a radiobutton,the filepath will change to Huse,Folii or Altele.
For example i tried to make _path :
Dim _path As String = IO.Path.Combine("C:\Descriere\Huse\")
then use the _path here:
Dim ioFile As New System.IO.StreamReader(_path + "a.txt")
but it didn't worked,for sure i do something wrong,but i can't find how or where to use that _path...
Here is the code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
On Error Resume Next
TextBox1.Clear()
If RadioButton1.Checked = True Then
Dim _path As String = IO.Path.Combine("C:\Descriere\Huse\")
End If
If RadioButton2.Checked = True Then
Dim _path As String = IO.Path.Combine("C:\Descriere\Folii\")
End If
If RadioButton3.Checked = True Then
IO.Path.
Dim _path As String = IO.Path.Combine("C:\Descriere\Altele\")
End If
Dim ioFile As New System.IO.StreamReader(_path + "a.txt")
Dim lines As New List(Of String)
Dim rnd As New Random()
Dim line As Integer
While ioFile.Peek <> -1
lines.Add(ioFile.ReadLine())
End While
line = rnd.Next(lines.Count + 1)
TextBox1.AppendText(lines(line).Trim())
ioFile.Close()
ioFile.Dispose()
Dim ioFile2 As New System.IO.StreamReader(path:=+"core.txt")
Dim lines2 As New List(Of String)
Dim rnd2 As New Random()
Dim line2 As Integer
While ioFile2.Peek <> -1
lines2.Add(ioFile2.ReadLine())
End While
line2 = rnd2.Next(lines2.Count + 1)
TextBox1.AppendText(lines2(line2).Trim())
ioFile2.Close()
ioFile2.Dispose()
Dim ioFile3 As New System.IO.StreamReader(path:=+"x.txt")
Dim lines3 As New List(Of String)
Dim rnd3 As New Random()
Dim line3 As Integer
While ioFile3.Peek <> -1
lines3.Add(ioFile3.ReadLine())
End While
line3 = rnd3.Next(lines3.Count + 1)
TextBox1.AppendText(lines3(line3).Trim())
ioFile3.Close()
ioFile3.Dispose()
TextBox1.Text = Replace(TextBox1.Text, "BRAND", TextBox2.Text)
TextBox1.Text = Replace(TextBox1.Text, "MODEL", TextBox3.Text)
Dim count As Integer = 0
count = TextBox1.Text.Split(" ").Length - 1
Label5.Text = "Caractere:" & Len(TextBox1.Text)
End Sub
You are using IO.Path.Combine but you have nothing to Combine at the place of use in your code. You have to use IO.Path.Combine later in your code because this is a method to Combine part of a path and a filename e.g. set your _path first and combine in a second step. Please note this code is not tested for your needs, because your coding is not clear to me.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim directoryName As String = "D:\"
On Error Resume Next
TextBox1.Clear()
If RadioButton1.Checked = True Then
directoryName = "D:\Descriere\Huse"
End If
If RadioButton2.Checked = True Then
directoryName = "D:\Descriere\Folii"
End If
If RadioButton3.Checked = True Then
'//--- IO.Path.
directoryName = "D:\Descriere\Altele"
End If
Dim ioFile As New System.IO.StreamReader(System.IO.Path.Combine(directoryName, "a.txt"))
...
Dim ioFile2 As New System.IO.StreamReader(System.IO.Path.Combine(directoryName, "core.txt"))
...
Dim ioFile3 As New System.IO.StreamReader(System.IO.Path.Combine(directoryName, "x.txt"))
...
End Sub
Please use the debugger of your IDE because your code isn't clean e.g. a hanging aroung IO.Path.

Score not being calculated correctly

Hi I'm created a program for a project and I've now started running some tests and the score for the user isn't being calculated correctly and I believe that it can't compare the answer given to the correct answer. I'm very confused and need any help that can be given. My code looks like this, any confusing parts and I'll try and explain.
Imports System.IO
Public Class QuestionScreen
Dim score As Integer = 0
Dim count As Integer
Dim Difficulty_ext As String
Dim questions, answers As New List(Of String)()
Private i As Integer
Sub ReadFile()
If Main.Diff_DDown.Text = "Easy" Then
Difficulty_ext = "questions - Easy"
ElseIf Main.Diff_DDown.Text = "Medium" Then
Difficulty_ext = "questions - Medium"
Else
Difficulty_ext = "questions - Difficult"
End If
Randomize()
Dim countline = File.ReadAllLines("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt").Length
Dim numline As Integer
Dim values() As String
Using sr As New StreamReader("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt")
While Not sr.EndOfStream
values = sr.ReadLine().Split(","c)
questions.Add(values(0))
answers.Add(values(1))
End While
End Using
numline = Int(Rnd() * countline)
For i As Integer = 0 To numline
Question.Text = questions(i)
Act_ANS.Text = answers(i)
Next
End Sub
Private Sub Pass_Btn_Click(sender As Object, e As EventArgs) Handles Pass_Btn.Click
If count < 10 Then
Call ReadFile()
count = count + 1
Ans_TxtBx.Text = ""
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
End If
End Sub
Public Sub Submit_Btn_Click(sender As Object, e As EventArgs) Handles Submit_Btn.Click
If count < 10 Then
Call ReadFile()
count = count + 1
If Ans_TxtBx.Text = answers(i) Then
score = score + 1
End If
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
count = 0
End If
Ans_TxtBx.Text = ""
End Sub
Private Sub QuestionScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call ReadFile()
End Sub
End Class
OK..... Try this, I have debugged your code trying to leave it pretty much as you had it, there were a number of problems, nothing major just a few lines of code in the wrong place....
Imports System.IO
Public Class Form1
Dim score As Integer = 0
Dim count As Integer
Dim Difficulty_ext As String
Dim questions, answers As New List(Of String)()
Private i As Integer
Sub ReadFile()
If Diff_DDown.Text = "Easy" Then
Difficulty_ext = "questions - Easy"
ElseIf Diff_DDown.Text = "Medium" Then
Difficulty_ext = "questions - Medium"
Else
Difficulty_ext = "questions - Difficult"
End If
Randomize()
Try
Dim countline = File.ReadAllLines("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt").Length
Dim numline As Integer
Dim values() As String
' clear the list of questions and answers
answers.Clear()
questions.Clear()
'''''''''''''''''''''''''''''''''''''''''
Using sr As New StreamReader("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt")
While Not sr.EndOfStream
values = sr.ReadLine().Split(","c)
questions.Add(values(0))
answers.Add(values(1))
End While
End Using
numline = Int(Rnd() * countline)
For i = 0 To numline
Question.Text = questions(i)
Act_ANS.Text = answers(i)
Next
Catch ex As Exception
End Try
End Sub
Private Sub Pass_Btn_Click(sender As Object, e As EventArgs) Handles Pass_Btn.Click
If count < 10 Then
count = count + 1
Ans_TxtBx.Text = ""
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
End If
Call ReadFile() ' move this to the bottom
End Sub
Public Sub Submit_Btn_Click(sender As Object, e As EventArgs) Handles Submit_Btn.Click
If count < 10 Then
count = count + 1
If Ans_TxtBx.Text = answers(i - 1) Then ' need to subtract 1 here
score = score + 1
End If
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
count = 0
End If
Ans_TxtBx.Text = ""
Call ReadFile() ' move this to the bottom
End Sub
Private Sub QuestionScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call ReadFile()
End Sub
End Class

looping to add 271 records into my dictionary it only add 150 then exit the subroutine. (VB.net 2015)

For VB.net 2015
I'm a new programmer. I've been warping my brain around this for 2 days. Can seem to see the problem. It seems I can only add 150 records to the dictionary. I'm not sure where its failing in the code. I'm not getting any errors or warnings.
Really hope someone can give me a hand.
Heres a link to my file I'm working with.
https://drive.google.com/file/d/0B1zf86jcRv49Y1lCMHRvNWt4UFk/view?usp=sharing
P.S. Sry about the crappy coding skill :-)
Imports System
Imports System.IO
Public Class Form1
Dim xx As Integer = 0
Private MainDataList As New Dictionary(Of String, List(Of String))
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim temp1 As List(Of String)
'MsgBox(xx)
If MainDataList.ContainsKey(TextBox1.Text) Then
temp1 = MainDataList.Item(TextBox1.Text)
Label1.Text = temp1(0)
Beep()
Else
Label1.Text = "Not Found"
Beep()
Beep()
End If
TextBox1.Text = ""
End Sub
Private Sub GetData()
Dim ReadDataLine(50000) As String
Try
' Open the file using a stream reader.
Using sr As New StreamReader("C:\Inventory\Invatory.csv")
'Dim line As String
' Read the stream to a string and write the string to the console.
ReadDataLine(0) = sr.ReadLine
Do While (sr.EndOfStream = False)
ReadDataLine(xx) = sr.ReadLine
'AddToList(ReadDataLine) ' pars data into main list
'MsgBox(sr.ReadLine)
xx = xx + 1
Loop
sr.Close()
'line = sr.ReadLine()
End Using
Catch e As Exception
'MsgBox(xx)
MsgBox("The file could not be read:")
MsgBox(e.Message)
End Try
'MsgBox(xx)
'xx = 0
For Each i As String In ReadDataLine
AddToList(i)
'MsgBox(xx)
'xx = xx + 1
Next
End Sub
Private Sub AddToList(data As String)
Dim barCode As String = ""
Dim steps As Integer = 1
Dim LastPos As Integer = 2
Dim datalist As New List(Of String)
Dim firstPass As Boolean = False
For i = 2 To Len(data)
'Find end of cell
If Mid(data, i, 1) = "," Then
If firstPass = False Then
barCode = Mid(data, LastPos, i - 2)
'MsgBox(Mid(data, LastPos, i - 2))
LastPos = i
firstPass = True
Else
Dim temp As Integer = i - LastPos
datalist.Add(Mid(data, LastPos + 1, temp - 1))
'MsgBox(Mid(data, LastPos + 1, temp - 1))
LastPos = i
End If
End If
Next
MainDataList.Add(barCode, datalist)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GetData()
Label1.Text = "Ready!"
Me.Show()
TextBox1.Focus()
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
End Class

Datagridview doesnt auto select first row after filling datasource

i have datagridview with 4 columns
[Nam] , [ID] , [Shuru] , [Payan]
second column ([ID]) is hidden and is used to gather some details about the data.
this is the Load code :
Private Sub SalMali_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.DGV_SalMaliTableAdapter.Fill(Me.FDBDataSet.DGV_SalMali)
End Sub
which retrieves everything in DGV_SalMali table.
i know that datagridview automatically selects first row after a fill so i put a function in the Selection Change to retrieve data. here is the code :
Private Sub DGV_SalMaliDataGridView_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DGV_SalMaliDataGridView.SelectionChanged
refreshDT()
End Sub
Public Sub refreshDT()
Dim cnt As Integer = DGV_SalMaliDataGridView.Rows.Count
If cnt = 0 Then
GoTo line
End If
unlockAll()
Dim sel As String = DGV_SalMaliDataGridView.SelectedRows(0).Cells(1).Value
Dim dt As New DataTable
dt = SalMaliTA.GetData_SalMali_B_ID(sel)
Dim dtr As DataRow = dt.Rows(0)
TextBox1.Text = dtr.Item(4)
MaskedTextBox1.Text = mc.MtoS(dtr.Item(1))
MaskedTextBox2.Text = mc.MtoS(dtr.Item(2))
CheckBox1.Checked = dtr.Item(3)
Exit Sub
line:
lockAll()
End Sub
but when I call refreshDT() the selection doesn't work anymore. it throws an error on line 8 of refreshDT()
sub { exactly here : Dim sel As String = DGV_SalMaliDataGridView.SelectedRows(0).Cells(1).Value }
Thrown: "Index was out of range. Must be non-negative and less than
the size of the collection."
(System.ArgumentOutOfRangeException) Exception Message = "Index was
out of range. Must be non-negative and less than the size of the
collection.", Exception Type = "System.ArgumentOutOfRangeException"
datagridview has rows and i dont know what the problem is.
thanks for help.
you're currently checking if there are any rows but not any selected rows:
Public Sub refreshDT()
Dim cnt As Integer = DGV_SalMaliDataGridView.Rows.Count
If cnt = 0 Then
lockAll()
Exit Sub
End If
If DGV_SalMaliDataGridView.SelectedRows.Count = 0 Then
DGV_SalMaliDataGridView.Rows(0).Selected = true
End If
unlockAll()
Dim sel As String = DGV_SalMaliDataGridView.SelectedRows(0).Cells(1).Value
Dim dt As New DataTable
dt = SalMaliTA.GetData_SalMali_B_ID(sel)
Dim dtr As DataRow = dt.Rows(0)
TextBox1.Text = dtr.Item(4)
MaskedTextBox1.Text = mc.MtoS(dtr.Item(1))
MaskedTextBox2.Text = mc.MtoS(dtr.Item(2))
CheckBox1.Checked = dtr.Item(3)
End Sub

Listview - select mosti similar item to value

How would one select item in listview (first column) that is most similar to string value from e.g. label or textbox.
Listview is populated with this code :
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListView1.Items.Clear()
ListView1.View = System.Windows.Forms.View.Details
ListView1.Columns.Add("COL1", 100, HorizontalAlignment.Left) 'KONTO
ListView1.Columns.Add("COL2", 140, HorizontalAlignment.Left) 'NAZIV
Dim FilePath As String = "W:\GLAVNI\KOR14\"
Dim DBF_File As String = "MATIKGL"
Dim ColName As String = "KONTO"
'Dim naz As String
Using con As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV")
con.Open()
Using cmd As New OleDbCommand("SELECT * FROM MATIKGL ORDER BY KONTO, NAZIV", con)
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
While (reader.Read())
Me.ListView1.Items.Add(reader("KONTO"))
'ListView1.Items(i).SubItems.Add(rdr.Item("YourColumnName").ToString)
'BELOW SELECTS ALL ITEMS THAT STARTS WITH 2020-
For i = 0 To ListView1.Items.Count - 1
If ListView1.Items(i).ToString.Contains("2020-") Then
Else
ListView1.Items.Remove(ListView1.Items(i))
End If
Next
End While
Else
End If
End Using
End Using
con.Close()
End Using
End Sub
I have one textbox and a button.
Textual input from textbox should be compared with all items in listview and closest should be selected. One more thing : All items are sorted alphabetically
Button code is :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListView1.MultiSelect = False
ListView1.FullRowSelect = True
Dim checkInt As Integer = FindItem(ListView1, "2020-" & TextBox1.Text)'this one is changed since all items starts with "2020-"& UCASE TEXT
If checkInt <> -1 Then
ListView1.Items(checkInt).Selected = True
ListView1.Focus()
Else
Label1.Text = "Search string not found"
End If
End Sub
UPDATED CODE
Dim checkInt As Integer = FindItem(ListView1, "2020-" & TextBox3.Text)
If checkInt <> -1 Then
TextBox4.Focus()
Else
Label14.Text = "NEMA"
On Error GoTo ext
Dim li As ListViewItem
ListView1.SelectedItems.Clear()
ListView1.HideSelection = False
li = ListView1.FindItemWithText("2020-" & UCase(TextBox3.Text))
If Not (li Is Nothing) Then
Me.ListView1.Focus()
li.Selected = True
li.EnsureVisible()
ElseIf li Is Nothing Then
li = ListView1.FindItemWithText("2020-" & Strings.Left(TextBox3.Text, 1))
Me.ListView1.Focus()
li.Selected = True
li.EnsureVisible()
Else
End If
Exit Sub
ext:
TextBox3.Text = ""
TextBox3.Focus()
Label14.Text = "String not found"
End If
This one works.
I know it's not the best solution but it's working.
Could fixed this without your help, thank you Phillip Trelford
Define a function to score two strings for closeness then use LINQ to find the lowest score, i.,e.
' Example score function
Function Score(a As String, b As String) As Integer
Dim index = 0
While index < a.Length And index < b.Length
Dim diff = Math.Abs(AscW(a(index)) - AscW(b(index)))
If diff <> 0 Then Return diff
index += 1
End While
Return Math.Abs(a.Length - b.Length)
End Function
Function Closest(searchWord As String, words As String()) As String
Dim ordered =
From w In words
Select Word = w, Score = Score(w, searchWord)
Order By Score
Return ordered.First().Word
End Function
Sub Main()
Dim words = {"Alpha", "Apple", "Ask"}
Dim searchWord = "Ann"
Dim word = Closest(searchWord, words)
Console.WriteLine(word)
End Sub
Update
To select the value in a WinForms ListView, you need to do roughly this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListView1.MultiSelect = False
ListView1.FullRowSelect = True
Dim prefix = "2020-"
' Extract items from Listview
Dim items = New List(Of String)()
For Each item In ListView1.Items
items.Add(item)
Next
Dim words = items.ToArray()
Dim searchWord = TextBox1.Text
Dim resultWord = Closest(searchWord, words)
'this one is changed since all items starts with "2020-"& UCASE TEXT
Dim checkInt As Integer = FindItem(ListView1, prefix & resultWord)
If checkInt <> -1 Then
ListView1.Items(checkInt).Selected = True
ListView1.Focus()
Else
Label1.Text = "Search string not found"
End If
End Sub