Vb.net List within a list - vb.net

So far I have the following code below. How to display each list value to textboxes?
Dim list As New List(Of String)
list.Add(dgvData.SelectedCells(0).Value.ToString)
list.Add(dgvData.SelectedCells(1).Value.ToString)
list.Add(dgvData.SelectedCells(2).Value.ToString)
list.Add(dgvData.SelectedCells(4).Value.ToString)
Dim val As String
For Each val In list
' MsgBox(val)
Next

Add your code in the CellEnter Event. You don't need to declare the list.
Private Sub YourDataGrid_CellEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles YourDataGrid.CellEnter
txtbox1.Text = YourDataGrid.Item(col, row).Value.ToString
txtbox2.Text = YourDataGrid.Item(col, row).Value.ToString
txtbox3.Text = YourDataGrid.Item(col, row).Value.ToString
txtbox4.Text = YourDataGrid.Item(col, row).Value.ToString
end sub

Related

How to add user input to array list

the program is supposed to take the text in from the text boxes, combine it into a NewCustomer element, and then display it in a listbox. Below is the code i'm supposed to add to, i've tried lstCustomer.add(txtFirstname.text) but it turned to be an error. Thanks in advance for helping.
Public Class Form1
Private myCustomers As New ArrayList
Public ReadOnly Property SelectedCustomer As Customer
Get
Dim index As Integer = lstCustomer.SelectedIndex
If index <> -1 Then
Return lstCustomer.Items(index)
Else
Return Nothing
End If
End Get
End Property
Public Sub NewCustomer(ByVal fn As String, ByVal ln As String, ByVal a As Integer, ByVal e As String)
Dim temp As Customer
temp.FirstName = fn
temp.LastName = ln
temp.Age = a
temp.Email = e
myCustomers.Add(temp)
Me.lstCustomer.Items.Add(temp)
End Sub
Private Sub BtnTest_Click(sender As Object, e As EventArgs) Handles BtnTest.Click
NewCustomer("Homer", "Simpson", 40, "HSimpson#springf.com")
NewCustomer("Bruce", "Banner", 44, "green#giant.com")
End Sub
Public Sub displayCustomer(ByVal temp As Customer)
Me.TxtName.Text = temp.name
Me.TxtFirstName.Text = temp.FirstName
Me.TxtLastName.Text = temp.LastName
Me.TxtAge.Text = temp.Age
Me.TxtEmail.Text = temp.Email
End Sub
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click
lstCustomer.add(TxtFirstName.Text And TxtLastName.Text And TxtEmail.Text And TxtAge.Text)
End Sub
I suggest using data binding, this makes it easier to work with the ListBox. First make sure to override ToString in the Customer class to make is displayable in the ListBox
Public Class Customer
Public Property FirstName As String
Public Property LastName As String
Public Property Age As Integer
Public Property Email As String
Public Overrides Function ToString() As String
Return $"{FirstName} {LastName} ({Age}) {Email}"
End Function
End Class
Then we use a List(Of Customer) instead of an ArrayList. The advantage is that the List(Of ) is strongly typed, i.e., its elements are of type Customer, where as the ArrayList has elements of type Object.
Also, we create a wrapper of type BindingList(Of Customer) to wrap our list to enable auto-updating of the ListBox. Example:
Public Class Form1
Dim customers As New List(Of Customer)
Dim customersBinding As BindingList(Of Customer)
Public Sub New()
InitializeComponent()
customersBinding = New BindingList(Of Customer)(customers)
lstCustomer.DataSource = customersBinding
End Sub
Private Sub NewCustomer(ByVal fn As String, ByVal ln As String, ByVal a As Integer, ByVal e As String)
Dim customer As New Customer With {
.FirstName = fn,
.LastName = ln,
.Age = a,
.Email = e
}
customersBinding.Add(customer)
lstCustomer.SelectedItem = customers(customers.Count - 1)
' or lstCustomer.SelectedIndex = customers.Count - 1
End Sub
Private Sub BtnTest_Click(sender As Object, e As EventArgs) Handles BtnTest.Click
NewCustomer("Homer", "Simpson", 40, "HSimpson#springf.com")
NewCustomer("Bruce", "Banner", 44, "green#giant.com")
End Sub
Public Sub DisplayCustomer(ByVal customer As Customer)
TxtFirstName.Text = customer.FirstName
TxtLastName.Text = customer.LastName
TxtAge.Text = customer.Age.ToString()
TxtEmail.Text = customer.Email
End Sub
Private Sub lstCustomer_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstCustomer.SelectedIndexChanged
Dim index As Integer = lstCustomer.SelectedIndex
If index >= 0 Then
DisplayCustomer(customers(index))
End If
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
NewCustomer(TxtFirstName.Text, TxtLastName.Text, CInt(TxtAge.Text), TxtEmail.Text)
End Sub
End Class
In the constructor we create the binding list and set it as data source of the ListBox.
See how Sub NewCustomer only adds the new customer to the binding list. This inserts the customer to the wrapped list as well and at the same time updates the ListBox.
We also automatically select the last inserted customer in the ListBox with
lstCustomer.SelectedItem = customers(customers.Count - 1)
or (easier)
lstCustomer.SelectedIndex = customers.Count - 1
We use the SelectedIndexChanged event to automatically display the customer in the textboxes when the user selects another customer in the listbox.
You could also extend data binding to automatically bind the customer objects to the textboxes. You will find a lot of online tutorials on this subject.

Visual basic / visual studio 2010 windows form loads blank

I am new to visual basic so hopefully this is a simple question. I have a menu with buttons to call different forms. The forms are designed and have labels and text fields and buttons and so on. From the main menu I have tried calling the forms two different ways. One way the forms open and look correct and function. The other way the form opens as a small blank square with no fields. Ultimately I want to create a set of List objects when the main menu opens and pass them back and forth to the other forms for input and processing. I'm using parallel Lists as a temporary database for a simple school lab. I just don't see what is wrong with the way I am calling the form. I haven't even bothered worrying about passing the List objects properly yet.
Public Class frmMain
Dim arrGames As New List(Of String)
Dim arrDates As New List(Of String)
Dim arrPrices As New List(Of Decimal)
Dim arrSeats As New List(Of Integer)
Private Sub btnEnterGames_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnterGames.Click
'NewEnter.Visible = True
Dim frmEnter As New NewEnter(arrGames, arrDates, arrPrices, arrSeats)
frmEnter.ShowDialog()
End Sub
Private Sub btnReports_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReports.Click
'Reports.Visible = True
Dim frmReports As New Reports(arrGames, arrDates, arrPrices, arrSeats)
frmReports.Visible = True
End Sub
Private Sub btnSellTickets_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSellTickets.Click
'SellTickets.Visible = True
Dim frmSell As New SellTickets(arrGames, arrDates, arrPrices, arrSeats)
frmSell.Visible = True
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Close()
End Sub
End Class
This is the code for the form NewEnter. I have the New routine which accepts the 4 Lists and basically does nothing else. Doing the "'NewEnter.Visible = True" in the main menu will load the form correctly but I have to comment out the New sub routine in the forms or there is an error.
Public Class NewEnter
Private _arrGames As List(Of String)
Private _arrDates As List(Of String)
Private _arrPrices As List(Of Decimal)
Private _arrSeats As List(Of Integer)
Sub New(ByVal arrGames As List(Of String), ByVal arrDates As List(Of String), ByVal arrPrices As List(Of Decimal), ByVal arrSeats As List(Of Integer))
' TODO: Complete member initialization
' _arrGames = arrGames
' _arrDates = arrDates
' _arrPrices = arrPrices
' _arrSeats = arrSeats
End Sub
Private Sub btnSaveGame_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveGame.Click
Dim arrGames As New List(Of String)
Dim arrDates As New List(Of String)
Dim arrPrices As New List(Of Decimal)
Dim arrSeats As New List(Of Integer)
Dim strGame As String
Dim strPrice As String
Dim strSeats As String
Dim intSeats As Integer
Dim decPrice As Decimal
Dim bolGameErr As Boolean
Dim bolDateErr As Boolean
Dim bolPriceErr As Boolean
Dim bolSeatErr As Boolean
strGame = txtGame.Text
strPrice = txtPrice.Text
strSeats = txtSeats.Text
'~~~~~~~~~~~~verify a game is entered
If String.IsNullOrEmpty(strGame) Or String.IsNullOrWhiteSpace(strGame) Then
bolGameErr = True
Else
'~~~~~~~~~~~~verify price is numeric
If IsNumeric(strPrice) Then
decPrice = strPrice
'~~~~~~~~~~~~~~~verify seats are numeric
If IsNumeric(strSeats) Then
intSeats = Convert.ToInt32(strSeats)
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ add elements to array lists
arrGames.Add(New String(strGame))
arrDates.Add(dtpDate.Text)
arrPrices.Add(New Decimal(decPrice))
arrSeats.Add(intSeats)
lblSaveSuccessful.Visible = True
ClearInput()
' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ add elements to array lists
Else
bolSeatErr = True
End If
Else
bolPriceErr = True
End If
End If
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Check flags for input errors
If bolDateErr = True Then
lblErr.Text = "Invalid date"
lblErr.Visible = True
End If
If bolGameErr = True Then
lblErr.Text = "Must enter a game name"
lblErr.Visible = True
txtGame.Focus()
End If
If bolDateErr = True And bolGameErr = True Then
lblErr.Text = "Must enter a game name and valid date"
lblErr.Visible = True
txtGame.Focus()
End If
If bolPriceErr = True Then
lblPriceErr.Visible = True
txtPrice.Text = ""
txtPrice.Focus()
End If
If bolSeatErr = True Then
lblSeatErr.Visible = True
txtSeats.Text = ""
txtSeats.Focus()
End If
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Check flags for input error
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Display output
Dim i As Integer
i = 0
lblData.Text = arrGames.Count.ToString
Do While i < arrGames.Count
lblData.Text = Convert.ToString(arrGames(i)) & " on " & Convert.ToString(arrDates(i)) & " Price: " & _
Convert.ToString(arrPrices(i)) & " Available Seats: " & Convert.ToString(arrSeats(i))
i += 1
Loop
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Display output
lblData.Visible = True
End Sub
Private Sub ClearInput()
'lblErr.Visible = False
'lblPriceErr.Visible = False
'lblSeatErr.Visible = False
txtGame.Text = ""
txtPrice.Text = ""
txtSeats.Text = ""
txtGame.Focus()
End Sub
Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Me.Visible = True
'Me.BackColor = Color.BurlyWood
'Me.ResumeLayout()
'Me.Activate()
'Me.Focus()
'Me.Show()
'Me.lblGameHdr.Visible = True
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Close()
End Sub
End Class
Add InitializeComponent() to your constructor class.
This is added by default to the New (constructor) function of all Visual Basic forms. It requires it to set-up the UI components on the form.

Change a label text with the forms name in a string eg. String1.label1.text

I am trying to create a Function that does everything automatically. Here is my current code:
Public Sub IncrementValueBeta(SlideDescription As String, SlideNumber As Integer, FormName As String)
ChangeSlide (SlideNumber)
MsgBox ("Test: " + SlideDescription)
AddClicks = FormName.ClickedTimes.Text + 1
FormName.ClickedTimes.Text = AddClicks
End Sub
This will add a number to the value but I am trying to make the code more concise without having to do if FormName = "Slide1" a 1000 times as it is a huge questionnaire.
The user will type "FormName" e.g., "Form1". In the code, it will use it like FormName.ClickedTimes.Caption = AddClicks so in the slide if the slide was 25 clicks it would be 26 that's already working but only if I do Slide3 not FormName is there a way I can do this? If you know how, can you help me because it will be a real pain if I have to do If bah = "bah" then elseif bah = "bah" then 1000 times.
This will basically Change the text of the Form label, to Eg, the user has clicked yes i like sports, the code will load the module/class and change label1.text to +1 clicks and it will change label2.text to "Question 2" but it doesn't know what form it is so it will use the text in FormName that was given with the arguments to find out what form it is editing. thats what im trying to accomplish here
In short, i just want it to find the form from FormName and View FormName.Label1.text = "" as Form1.Label1.text = ""
*Assuming there is only one instance of the desired Form, try something like this:
Public Sub IncrementValueBeta(SlideDescription As String, SlideNumber As Integer, FormName As String)
ChangeSlide(SlideNumber)
Dim frmTarget As Form = Nothing
For Each frm As Form In Application.OpenForms
If frm.Name.ToUpper = FormName.ToUpper Then
frmTarget = frm
Exit For
End If
Next
If Not IsNothing(frmTarget) Then
Dim matches() As Control = frmTarget.Controls.Find("ClickedTimes", True)
If matches.Length > 0 Then
AddClicks = matches(0).Text + 1
matches(0).Text = AddClicks
End If
End If
End Sub
I would also go with the way of using dictionaries.
Public Class Form1
Private slides As New Dictionary(Of Integer, String)
Private currentSlideNumber As Integer
Private currentSlideDescription As String
Public Sub IncrementByClick()
currentSlideDescription = slides(currentSlideNumber + 1)
currentSlideNumber += 1
ChangeSlide(currentSlideDescription)
End Sub
Public Sub ChangeSlide(ByVal slideDescription As String)
currentSlideNumber = SelectSlideNumberByDesc(slideDescription)
currentSlideDescription = slides(currentSlideNumber)
MessageBox.Show("Successfully changed the slide to slide no. " & currentSlideNumber)
End Sub
Private Function SelectSlideNumberByDesc(ByVal slideDesc As String)
Dim slideNumber As Integer
For Each slide In slides
If slide.Value = slideDesc Then
slideNumber = slide.Key
Exit For
End If
Next
Return slideNumber
End Function
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
slides.Add(1, "SLIDE_ONE")
slides.Add(2, "SLIDE_TWO")
slides.Add(3, "SLIDE_THREE")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ChangeSlide(TextBox1.Text)
End Sub
Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
IncrementByClick()
End Sub
End Class
With by clicking button1, the slide will change according to the slide description the user have entered in the textbox.
By clicking btnNext, next slide will load accordingly.
OO way is way better but this should be enough to show it.

read single word from listbox vb

I have an order form I created in VB.NET and I have a ListBox that is populated by order. You can double click on the order and it populates the order number in the order form. The problem I'm having is that it populates the TextBox with both the order number and the persons name. How can I use a delimiter to only pull out the order number and not the name also.
Imports Business_Objects
Public Class frmSummary
Private ctrl As Controller
Dim listID As ArrayList
Private Sub frmSummary_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ctrl = CType(MdiParent, frmMain).ctrl
Dim list As ArrayList
list = ctrl.GetOrders
Dim order As Business_Objects.Order
For Each order In list
lstOrders.Items.Add(order.ID & "," & " " & order.Server)
Next
End Sub
Private Sub lstOrders_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstOrders.DoubleClick
Dim result As Boolean = False
If lstOrders.Text <> "" Then
result = True
Dim frm As New OrderForm
frm.MdiParent = Me.MdiParent
frm.Show()
frm.txtOrderNo.Text = lstOrders.Text
frm.btnFetch.PerformClick()
Else
MessageBox.Show("there are no orders here to click")
End If
End Sub
Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
lstOrders.Items.Clear()
ctrl = CType(MdiParent, frmMain).ctrl
Dim list As ArrayList
list = ctrl.GetOrders
Dim order As Business_Objects.Order
For Each order In list
lstOrders.Items.Add(order.ID & " " & order.Server)
Next
End Sub
End Class
If all of your data is being stored as a single field, or something like:
4322305 John Smith Carrots $3.00
845825 Sam White Oranges $1.25
Then you can read each record as a string, and then use split that into an array based on " " as your delimiter.
The code would look something like:
dim myArray as string() = myLongTextRecord.Split(" ")
And in that format,
textBoxName.Text = myArray[1]
You're almost there. You could use the split function, but another approach would be to add the Order object directly to the listbox and not text.
Private Sub frmSummary_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ctrl = CType(MdiParent, frmMain).ctrl
Dim list As ArrayList
list = ctrl.GetOrders
Dim order As Business_Objects.Order
For Each order In list
lstOrders.Items.Add(order)
Next
End Sub
Private Sub lstOrders_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstOrders.DoubleClick
Dim result As Boolean = False
If lstOrders.Text <> "" Then
result = True
Dim frm As New OrderForm
frm.MdiParent = Me.MdiParent
frm.Show()
frm.txtOrderNo.Text = DirectCast(lstOrders.SelectedItem, Order).ID.ToString
frm.btnFetch.PerformClick()
Else
MessageBox.Show("there are no orders here to click")
End If
End Sub
You'll need to go into the Order object and override the .ToString function so that the text in the Listbox displays whatever value you want (ie. Return ID & "," & " " & Server)

vb2008 search through listbox using textbox

hi I have a form that find, or should I say filter, the items in a listbox using a textbox. I have a textbox used for searching and a listbox populated with items from database. Now, say listbox items include apple, banana, berry, cashew, lemon, mango, peanut. If I typed 'b' on the textbox, listbox only show banana and berry..if I typed 'ba' then listbox only show banana but if I typed 'be' then it shows berry and so on. I already got this working (with the code marked as commented in the txtSearch event). My problem is that how can I bring the items in the listbox back when the user strike the backspace? Because, say I have banana and berry in the listbox now, when I erased the text that I typed in the textbox it should list back all the items again so that if I want to search another item it will be filtered again. thanks in advance.
Code Update
Public Class Glossary
Private Sub Glossary_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call List()
Refreshlist()
End Sub
Private Sub List()
Dim myCmd As New MySqlCommand
Dim myReader As MySqlDataReader
Dim myAdptr As New MySqlDataAdapter
Dim myDataTable As New DataTable
Call Connect()
With Me
STRSQL = "Select word from glossary"
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
myReader = myCmd.ExecuteReader
If (myReader.Read()) Then
myReader.Close()
myAdptr.SelectCommand = myCmd
myAdptr.Fill(myDataTable)
lstword.DisplayMember = "word"
lstword.ValueMember = "word"
If myDataTable.Rows.Count > 0 Then
For i As Integer = 0 To myDataTable.Rows.Count - 1
lstword.Items.Add(myDataTable.Rows(i)("word"))
Next
End If
End If
'lstword.Items.Clear()
'lstword.Items.AddRange(word.Where(Function(word) word.ToString().Contains(txtSearch.Text)).ToArray())
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
myReader = Nothing
myCmd = Nothing
myConn.Close()
Call Disconnect()
End With
End Sub
Dim word As List(Of Object)
Private Sub Refreshlist()
lstword.Items.Clear()
lstword.Items.AddRange(word.Where(Function(word) word.ToString().Contains(txtSearch.Text)).ToArray())
End Sub
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
lstword.Items.Clear()
lstword.Items.AddRange(word.Where(Function(word) word.ToString().Contains(txtSearch.Text)).ToArray())
Refreshlist()
'Call List()
'lstword.BeginUpdate()
'Try
' ' keep track of the "non-searched items" '
' Dim word As New List(Of Object)
' lstword.SelectedIndices.Clear()
' If txtSearch.Text.Length > 0 Then
' For index As Integer = 0 To lstword.Items.Count - 1
' Dim item As String = lstword.Items(index).ToString()
' If item.IndexOf(txtSearch.Text, StringComparison.CurrentCultureIgnoreCase) >= 0 Then
' lstword.SelectedIndices.Add(index)
' Else
' ' this item was not searched for; we will remove it '
' word.Add(index)
' End If
' Next
' ' go backwards to avoid problems with indices being shifted '
' For i As Integer = word.Count - 1 To 0 Step -1
' Dim indexToRemove As Integer = word(i)
' lstword.Items.RemoveAt(indexToRemove)
' Next
' End If
'Finally
' lstword.EndUpdate()
'End Try
End Sub
End Class
The first step is to store the items in off-screen memory. For instance:
Dim words As List(Of Object)
Then when you refresh the list box, only populate it with the items from that in-memory list which match the current criteria:
lstword.Items.Clear()
lstword.Items.AddRange(
words.FindAll(
Function(word) Return word.ToString().Contains(txtSearch.Text)
).ToArray()
)
Or, using LINQ:
lstword.Items.Clear()
lstword.Items.AddRange(
words.Where(
Function(word) word.ToString().Contains(txtSearch.Text)
).ToArray()
)
UPDATE
Since you seem to be having trouble getting it working, and it's hard to say what's wrong with your code without actually seeing it, here's a complete working example:
Public Class Form1
Dim words As New List(Of Object)(New String() {"apple", "banana", "berry", "cashew", "lemon", "mango", "peanut"})
Private Sub RefreshList()
lstword.Items.Clear()
lstword.Items.AddRange(
words.Where(
Function(word) word.ToString().Contains(txtSearch.Text)
).ToArray()
)
End Sub
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
RefreshList()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
RefreshList()
End Sub
End Class
UPDATE 2
I tried using your code with my recommended suggestions and it worked fine. Here's the code that worked for me. Try it and let me know if it doesn't work for you:
Public Class Glossary
Private Sub Glossary_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
List()
Refreshlist()
End Sub
Private Sub List()
word.AddRange(New String() {"apple", "banana", "berry", "cashew", "lemon", "mango", "peanut"})
End Sub
Private word As New List(Of Object)()
Private Sub Refreshlist()
lstword.Items.Clear()
lstword.Items.AddRange(word.Where(Function(word) word.ToString().Contains(txtSearch.Text)).ToArray())
End Sub
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
Refreshlist()
End Sub
End Class
If that works, then all you need to do is change the List method to load from the database instead of being a hard-coded list.
Get your initial list off the database, pop it in a List class e.g List.
The use your search text to select all the matching items and put them in the list box. Blank search text you just put all of them in.
You might want to have a look at Foreach and List.FindAll as well.