VB.net update list items from file - vb.net

I click a button (with this code) to load lines from file "testexam" into a a listbox "lstHere". Testexam will be updated by another program and I want a code to copy new lines of "testexam" to the bottom of "lstHere". Secondly the selected index should come to the first item of the new list. Any help will be greatly appreciated.
Private Sub
Dim MReader As New StreamReader("C:\Users\Sparrow\testexam.txt")
Dim this1 As String = ""
Dim thisline(6000) As String
Dim i As Integer = 0
Do Until MReader.Peek = -1
this1= MReader.ReadLine
thisline(i)= this1
lstHere.Items.Add(thisline(i))
'go to the next line.
i = i + 1
Loop
End Sub

I don't know how you are trying to implement this, but it works with different buttons.
Button1:
'Add the selected item to the top
ListBox1.Items.Insert(0, ListBox1.SelectedIndex)
Button2:
'Delete duplicates
Dim items(ListBox1.Items.Count - 1) As Object
ListBox1.Items.CopyTo(items, 0)
ListBox1.Items.Clear()
ListBox1.Items.AddRange(items.AsEnumerable().Distinct().ToArray())

Related

How to make a foreach button in vba that saves values for an array of textboxes?

I have an List in a different form , and the values that are located inside the text boxes are retrieved from a list in a different form , my problem is that i cannot delete the values all at once because they come from a view and i'm not allowed to change multiple tables all at once, so my solution is to create an array with all my text boxes and to turn the value to null 1 by 1 and save them individual so that i don't get that error.
I've tried different solutions like saving everything at once.
Private Sub Comando28_Click()
Dim strTextBoxes(1 To 5) As String
tbAplic = Me.TbUAplicacion.Value
tbUsr = Me.tbuUsuario.Value
tbMail = Me.tbuMailUsuario.Value
tbnmbre = Me.tbuNombrePersona.Value
tbAppld = Me.tbuApellidosPersona.Value
tbDni = Me.tbuDNIPersona.Value
Dim ITM As strTextBoxes.ITM
For Each ITM In strTextBoxes.ITM
If ITM = Not Null Then ITM = Null
Guardar_Click '<---- this is a macro which I use to save the items new value
Next ITM
End Sub
the error it gives me when pressing the button that should make the action is as follows:
the user-defined type has not been defined
Try this:
Private Sub Comando28_Click()
Dim strTextBoxes(1 To 5) As String
tbAplic = Me.TbUAplicacion.Value
tbUsr = Me.tbuUsuario.Value
tbMail = Me.tbuMailUsuario.Value
tbnmbre = Me.tbuNombrePersona.Value
tbAppld = Me.tbuApellidosPersona.Value
tbDni = Me.tbuDNIPersona.Value
Dim ITM As String
Dim Item As Long
For Item = LBound(strTextBoxes) To UBound(strTextBoxes)
ITM = strTextBoxes(Item)
If ITM <> "" Then ITM = ""
Guardar_Click '<---- this is a macro which I use to save the items new value
Next
End Sub

VB.NET How to add Event Handler to ComboBoxColumn located in programmatically created controls?

I've got part of my code that creates a tab in a tabcontrol, and then fills it with a datagridview which contains a couple columns that are DataGridViewComboBoxColumn.
It looks like this:
Private Sub NewTabPage()
Dim TabPageCount As Integer = RacerOrderTAB.TabPages.Count
RacerOrderTAB.TabPages.Add(TeamNames(TabPageCount)) 'teamnames() is an array of team names
Dim CurrentTabPage = RacerOrderTAB.TabPages(TabPageCount)
Dim GridToAdd As New DataGridView
GridToAdd.Size = CurrentTabPage.Size
GridToAdd.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
GridToAdd.Location = New Point(CurrentTabPage.Location.X, CurrentTabPage.Location.Y)
GridToAdd.Columns.Add("ShiftCOL", "Shift Name")
GridToAdd.Name = "grid_" & CurrentTabPage.Text
For y As Integer = 1 To ShiftSetup.racerspershift 'add extra column for each racer in shift
Dim cmb As New DataGridViewComboBoxColumn
cmb.HeaderText = "Racer" & y
cmb.Name = "Racer_" & y
cmb.MaxDropDownItems = AmountOfRacers
cmb.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton
GridToAdd.Columns.Add(cmb)
Next
RacerOrderTAB.TabPages(TabPageCount).Controls.Add(GridToAdd)
End Sub
But I've been having difficulty in adding an eventhandler for the comboboxes. What I want to happen is that when a combobox is clicked and opened, I populate it with the items I want.
I managed to vaguely get it working by adding:
AddHandler GridToAdd.EditingControlShowing, AddressOf <sub name>
but then have been unable to figure out which combobox was clicked, and how to populate it. It's also been requiring like four clicks before the drop list will appear. I'm only slightly very confused.
Thanks for any advice; these DataGridViewComboBoxColumns [deep breath] have been confusing me a lot!
It may be a little hacky but it should do what you are asking… hopefully. I created two List(Of String) variables. AllRacers contains all the racers… i.e. all the names we want to appear in a combo box such that there is no other combo box on that row that has an item selected. These names are what all combo boxes on all rows would initially contain in the selectable items list.
The other List(Of String) UsedRacers contains a list of all the “comboboxes” on the current row that have selected items. Each time a cell value is changed and it is one of the “combobox” column cells, then UsedRacers is cleared/updated to reflect the added/changed selected item on the current row.
When a “comboBox” cell value is changed, SetUsedRacersForRow is called…
Private Sub SetUsedRacersForRow(rowIndex As Int16)
UsedRacers.Clear()
Dim curValue = ""
For i = 1 To racersPerShift
If (Not (dgvRacers.Rows(rowIndex).Cells(i).Value Is Nothing)) Then
curValue = dgvRacers.Rows(rowIndex).Cells(i).Value.ToString()
If (Not (String.IsNullOrEmpty(curValue))) Then
UsedRacers.Add(curValue)
End If
End If
Next
End Sub
The code above loops through all the “combobox” cells in the given row and if a “combobox” cell has something selected, the selected value is added to the UsedRacers list.
Now that the selected items for all the “comboboxes” in that row are in the UsedRacers list, we can now loop through each “combobox” cell in that row and set the proper list of names. To help, a method is created that returns a DataGridViewComboBoxCell such that the names in the current UsedRacers list will NOT be in the DataGridViewComboBoxCell’s list of selectable names.
The only issue here would be with cells that currently have an item selected. Each “combobox” cell with an item selected will uniquely need to have its selected item in its list of items. To remedy this, a check is needed to see if the “combobox” cell contains a value. If the “combobox” cell DOES contain a selected value, then this value is also contained in the UsedRacers list. Since THIS cell is the cell that is in the UseRacers list… then we need to ADD this value to this cells items list. Otherwise, we would not be able to display the unique selection.
To keep the UsedRacers list consistent, we need to add this item directly to the individual “combobox” cell and not remove or alter the UsedRacers list as this will be used for the other “combobox” cells. In other words… whatever value is selected in a combo box, we need to make sure it is one of the items in the “combobox’s” list of selectable items. I hope that makes sense.
This can all be done in the DataGridViews CellChanged event.
Private Sub dgvRacers_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles dgvRacers.CellValueChanged
If (e.ColumnIndex >= 1 And e.ColumnIndex <= racersPerShift) Then
SetUsedRacersForRow(e.RowIndex)
For i = 1 To racersPerShift
Dim newCell As DataGridViewComboBoxCell = GetCurrentComboBoxCell()
If (Not (dgvRacers.Rows(e.RowIndex).Cells(i).Value Is Nothing)) Then
Dim curValue = dgvRacers.Rows(e.RowIndex).Cells(i).Value.ToString()
newCell.Items.Add(curValue)
newCell.Value = curValue
End If
dgvRacers.Rows(e.RowIndex).Cells(i) = newCell
Next
End If
End Sub
In the code above, a method GetCurrentComboBoxCell (below) returns a DataGridViewComboBoxCell such that the items in the combo boxes list of items does not contain any items that are in the UsedRacers list. Because of this, a check is needed (above) to see if the cell already contains a value. NOTE: the DataGridViewComboBoxCell returned will always contain a “blank” empty item. This is necessary to allow the user to “De-Select” any currently selected value and then make the “De-Selected” item available to the other combo box cells.
Public Function GetCurrentComboBoxCell() As DataGridViewComboBoxCell
Dim newComboCell = New DataGridViewComboBoxCell()
newComboCell.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton
newComboCell.FlatStyle = FlatStyle.Flat
newComboCell.Items.Add("")
For Each curRacer In AllRacers
If (Not UsedRacers.Contains(curRacer)) Then
newComboCell.Items.Add(curRacer)
End If
Next
Return newComboCell
End Function
Finally, putting all this together…
Dim racersInShift = 3
Dim AllRacers As List(Of String) = New List(Of String) From {"John", "Bobby", "Trent", "Josh", "Chapman", "Henry", "George", "Marvin"}
'Dim racersPerShift As Int16 = AllRacers.Count '<-- should be MAX value
Dim racersPerShift As Int16 = 4
Dim UsedRacers = New List(Of String)
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BuildGrid()
End Sub
Private Sub BuildGrid()
dgvRacers.Size = New Size(800, 200)
dgvRacers.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
'dgvRacers.Location = New Point(50, 200)
dgvRacers.Columns.Add("ShiftCOL", "Shift Name")
dgvRacers.Name = "RacersDGV"
dgvRacers.EditMode = DataGridViewEditMode.EditOnEnter
dgvRacers.AllowUserToAddRows = False
AddRacerColumns()
AddRacerRows()
End Sub
Private Sub AddRacerColumns()
Dim newColumn As DataGridViewComboBoxColumn
For i As Integer = 1 To racersPerShift
newColumn = GetNewComboBoxColumn("Racer" & i, "Racer " & i)
dgvRacers.Columns.Add(newColumn)
Next
End Sub
Private Sub AddRacerRows()
For i As Integer = 1 To racersInShift
Dim row As New DataGridViewRow
dgvRacers.Rows.Add(row)
Next
End Sub
Private Sub dgvRacers_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs)
‘See code above
End Sub
Private Sub SetUsedRacersForRow(rowIndex As Int16)
‘See code above
End Sub
Public Function GetCurrentComboBoxCell() As DataGridViewComboBoxCell
‘See code above
End Function
‘Lastly a method to set a whole `DataGridviewComboBoxColumn` which is used to initialize all the combo box columns
Public Function GetNewComboBoxColumn(colName As String, colHeader As String) As DataGridViewComboBoxColumn
Dim newComboCol = New DataGridViewComboBoxColumn()
newComboCol.DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton
newComboCol.FlatStyle = FlatStyle.Flat
newComboCol.Items.Add("")
newComboCol.HeaderText = colHeader
newComboCol.Name = colName
For Each curRacer In AllRacers
newComboCol.Items.Add(curRacer)
Next
Return newComboCol
End Function
I hope this helps, I am guessing there is an easier way to do this.

Adding records (Row/ Column) to DataGridView; Collection already belongs to a DataGridView control VB.NET

I'm looking for some help with an issue I am having.
I have multiple text files, in a folder. The folder can have an "unlimited" amount of text files in it, although typically 2-150 files
http://gyazo.com/5f314d1ca374abf9f813914609dd931d (images for this + below, can't embed due to lack of reputation)
Each file then contains an "unlimited" (although typically 0-20 lines) amount of data inside it. Line 1 being the "test number" and line 2 being the "test result" - as seen in the image above
My Data Grid View has 3 columns in it (Username, test number, test result) - as seen in the image above
When running my code below; first record being added to the Data Grid View works perfectly, but the second (or any record after the first) the error occurs:
http://gyazo.com/0d492b97d918853e62c55ee314f3f181 (image) or error message:
"System.InvalidOperationException: Collection already belongs to a
DataGridView control. This operation is no longer valid. at
System.Windows.Forms.DataGridViewCellCollection.Add(DataGridViewCelldataGridViewCell)
at SpellingBee.TeacherMultiResults.TeacherMultiResults_Load(Object
sender, EventArgs e)"
This error occurs on the DGVRow.Cells.Add(DGVCell) 'add cell to row
One thing I don't want to do is change any of my text file/ folder structures, even though I'm aware that it is currently inefficient storage.
How can I fix this error? I'm using VB.net (Visual Studios 2013)
If you need any more information, please just ask
Many thanks.
Imports System.Windows.Forms
Imports System.IO
Public Class TeacherMultiResults
Dim AmountOfFiles
Dim LineCount As Integer = 0
Dim FileName As IO.FileInfo
Dim DGVRow As New DataGridViewRow
Dim DGVCell As DataGridViewCell
Dim Username As String = ""
Dim TestNumber As Integer = 0
Dim TestResult As Integer = 0
Private Sub TeacherMultiResults_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim directory As New IO.DirectoryInfo(LoadForm.CurrentDirectory & "\UserResults\") 'selects directory
Dim FileNames As IO.FileInfo() = directory.GetFiles()
Dim Files As IO.FileInfo
For Each Files In FileNames 'list the names of all files in the specified directory
Username = Files.ToString
Username = (Username.Substring(0, Username.Length - 4)) 'removes the .txt from the name
Try
LineCount = File.ReadAllLines(LoadForm.CurrentDirectory & "\UserResults\" & Username & ".txt").Length 'amount of lines in file
If LineCount > 1 Then
Dim Information As New System.IO.StreamReader(LoadForm.CurrentDirectory & "\UserResults\" & Username & ".txt") 'opens file
LineCount = LineCount / 2 'halfs line count
For i = 0 To LineCount - 1
TestNumber = Information.ReadLine() 'reads line to variable
TestResult = Information.ReadLine() 'reads line to variable
i = i + 1 'adds one to i
DGVCell = New DataGridViewTextBoxCell 'create a new DGV text box cell
DGVCell.Value = Username 'add value to DGV text box cell
DGVRow.Cells.Add(DGVCell) 'add cell to row
DGVCell = New DataGridViewTextBoxCell 'create a new DGV text box cell
DGVCell.Value = TestNumber 'add value to DGV text box cell
DGVRow.Cells.Add(DGVCell) 'add cell to row
DGVCell = New DataGridViewTextBoxCell 'create a new DGV text box cell
DGVCell.Value = TestResult 'add value to DGV text box cell
DGVRow.Cells.Add(DGVCell) 'add cell to row
DGV_MultiResults.Rows.Add(DGVRow) 'add row to DGV
Next
Information.Close() 'Close read
End If
Catch ex As Exception 'if file won't read
MsgBox(ex.ToString) 'show error
Exit Try
End Try 'end of try
Next 'end of files
End Sub
I hope that somebody can help me with this issue, I understand it's fairly simple to fix most probably although I can't seem to find a solution to the error!
Many thanks, Toby.
When working with a DataGridView, it is generally easier to just build an object list and then bind it to the DGV using the built-in data binding features.
For your example, it would look like this:
' Read the files, build objects as you go and add them to a list
Dim lst = New List(Of TeacherMultiResults)
' Replace this part with your file reading code...
Dim t1 = New TeacherMultiResults With {.Username = "Bob", .TestNumber = 1, .TestResult = 75}
lst.Add(t1)
Dim t2 = New TeacherMultiResults With {.Username = "Rick", .TestNumber = 1, .TestResult = 85}
lst.Add(t2)
Dim t3 = New TeacherMultiResults With {.Username = "Zoe", .TestNumber = 1, .TestResult = 95}
lst.Add(t3)
' Bind the list to the DataGridView
Dim bindList = New BindingList(Of TeacherMultiResults)(lst)
Dim bindSrc = New BindingSource
bindSrc.DataSource = bindList
grid.DataSource = bindSrc
Your grid should display each item of your list.

updating textbox.text in a tabpage

I've got an app with numerous textboxes that's basically a form to fill out. There are several tabpages in a tab control. In saving the data, I simply loop through the textboxes, get their names and text and put that in a text file with a '|' as a seperator. That works great and I can see all my textboxes and the data in the text file. Now comes the problem. When I read the file back (to load saved data back into the form) it loops through the control name and changes the text to whatever was in the file. It works fine with the textboxes that are on the form, but fails when it gets to the first textbox that is on a tabpage. How can I fix that? And if there's a better way to save the data, I'm all ears.
Here's the code that writes the file:
Private Sub savefile(file As String)
Dim ctl As Control = Me
Dim sw As System.IO.StreamWriter
sw = My.Computer.FileSystem.OpenTextFileWriter(file, False)
Do
ctl = Me.GetNextControl(ctl, True)
If ctl IsNot Nothing Then
If TypeOf ctl Is TextBox Then
sw.WriteLine(ctl.Name.ToString.Substring(3) & "|" & ctl.Text)
End If
End If
Loop Until ctl Is Nothing
sw.Close()
End Sub
Here's the code that reads the file and updates the textboxes:
Private Sub ReadFile(filename)
Dim strfilename As String = filename
Dim num_rows, x, y As Integer
Dim strarray(1, 1) As String
Dim ctrl As Control = Me
'Check if file exist
If File.Exists(strfilename) Then
Dim tmpstream As StreamReader = File.OpenText(strfilename)
Dim strrecords() As String
Dim strfields() As String
'Load content of file to strLines array
strrecords = tmpstream.ReadToEnd().Split(vbCrLf)
' Redimension the array.
num_rows = UBound(strrecords)
ReDim strarray(num_rows, 2)
' Copy the data into the array.
For x = 0 To num_rows - 1
strfields = strrecords(x).Split("|")
For y = 0 To 1
strarray(x, y) = strfields(y)
Next
Next
' Display the data in listbox
For x = 0 To num_rows - 1
Dim tbxname As String = strarray(x, 0)
tbxname = Remove(tbxname) 'routine that removes invisible characters
tbxname = "tbx" & tbxname
MsgBox(tbxname) 'used to verify each file and which one fails
Me.Controls(tbxname).Text = strarray(x, 1)
Next
Else : MsgBox("File doesn't exist!")
End If
End Sub
I hope that's enough information. Thanks in advance for any help!!
I think the line Me.Controls(tbxname).text = strarray(x,1) does not address your TextBox in your tab control, you may need to find out how to address your textbox in the tab page.
Something like
Me.TabControl1.TabPages(0).Controls(tbxname).text = starray(x,1)

Getting data from a ListView into an array

I have a ListView control on my form set up like this in details mode:
What I would like to do, is get all the values of the data cells when the user presses the Delete booking button.
So using the above example, my array would be filled with this data:
values(0) = "asd"
values(1) = "BS1"
values(2) = "asd"
values(3) = "21/04/2010"
values(4) = "2"
This is my code so far:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim items As ListView.SelectedListViewItemCollection = _
Me.ManageList.SelectedItems
Dim item As ListViewItem
Dim values(0 To 4) As String
Dim i As Integer = 0
For Each item In items
values(i) = item.SubItems(i).Text
i = i + 1
Next
End Sub
But only values(0) gets filled with the first data cell of the selection (in this case "asd") and the rest of the array entries are blank. I have confirmed this with a breakpoint and checked the array entries myself.
I'm REALLY lost on this, and have been trying for about an hour now. Any help would be appreciated, thanks :)
Also please note that there can only be one row selection at once. Thanks.
Costin is right about needing to iterate the subitems and if you're sure that there'll only be one selection iterating through the items just confuse things, I'd write it as:
Dim values As New List(Of String)
If ManageList.SelectedItems.Count > 0 Then
For Each item As ListViewItem.ListViewSubItem In ManageList.SelectedItems(0).SubItems
values.Add(item.Text)
Next
End If
I don't know how you populate the list but for me it seems that you need to iterate the item.Subitems to get the values. I don't know VB but I think you can use a something like :
For i As Integer = 0 To item.SubItems.Count
values(i) = item.SubItems(i).Text
Try this instead..
Dim values() As String
If items.Count = 1 Then
subitems = items(0).SubItems
ReDim values(0 To subitems.Count - 1)
For i As Integer = 0 To subitems.Count
values(i) = subitems(i).Text
Next
Else
Throw New Exception("boom")
End If