Dynamic reading from file & displaying on form load - vb.net

I have 2 text files named sQue.txt containing single words in each lines (each word in each line) and sObj.txt also containing single word in each line (but no. of entries are more in this file than in sQue.txt).
Now, I have a blank form in which I want to read both the above files & display them in a manner such that:
Each entry from sQue.txt file gets displayed in separate labels in the form
All the entries of file sObj.txt are put in a CheckedListBox & this CheckedListBox appears for each label displayed in point 1. above.
Example:
sObj.txt contains 3 entries aaa, bbb & ccc (vertically i.e each in new line).
sQue.txt contains 5 entries p,q,r,s & t (vertically i.e each in new line).
Now, when the form loads, 3 labels are seen with texts aaa, bbb & ccc. Also 3 CheckedListBoxes are seen containg p,q,r,s & t in each box.
Can it be done? I'm trying to find a solution with no luck yet.
Please help.
Till now all I have is
Private Sub Form7_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim queue As String() = IO.File.ReadAllLines("C:\temp\sQue.txt")
Dim objects As String() = IO.File.ReadAllLines("C:\temp\sObj.txt")
For i = 0 To queue.Count - 1
'create labels here
For j=0 to objects.Count - 1
'create CheckedListBoxes
Next
Next
End Sub

It is easily done:
Private Sub Form7_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim theAppDirectory = IO.Path.GetDirectoryName(Application.ExecutablePath)
Dim queue As String() = IO.File.ReadAllLines(theAppDirectory & "\que.txt")
Dim objects As String() = IO.File.ReadAllLines(theAppDirectory & "\obj.txt")
Dim top As Integer = 10
Dim left As Integer = 10
Dim I As Integer = 0
Dim J As Integer = 0
Dim aLabel As Label
Dim aListCheckBox As CheckedListBox
Dim aPanel As New Panel
aPanel.Dock = DockStyle.Fill
aPanel.Top = 0
aPanel.Left = 0
aPanel.AutoScroll = True
For I = 0 To queue.Count - 1
aLabel = New Label
aLabel.Text = queue(I)
aLabel.Top = top
aLabel.Left = left
aListCheckBox = New CheckedListBox
aListCheckBox.Top = top
aListCheckBox.Left = left + 100
For J = 0 To objects.Count - 1
aListCheckBox.Items.Add(objects(J), False)
top += 20
Next J
'add event handlers here
aPanel.Controls.Add(aLabel)
aPanel.Controls.Add(aListCheckBox)
Next I
Me.Controls.Add(aPanel)
End Sub
This assumes that you want the files to be in the same directory as the executable.
Also no event handlers are added. You will need to determine what event handlers you want and add them when you create the controls.

Related

Datagridview not displaying tab character

I use a visual basic program to get information from another program, which we'll call ProgramX.
ProgramX has built in functionality to generate tab-delimited tables, which many users copy over to Excel. My goal(which I've acheived) is to generate and collect upwards of 1,000 of these tables and have the results ready for the user to copy/paste into Excel all at once instead of one at a time. My Dataset keeps the tab-delimited records just as I would like them.
The issue is that when I display my dataset/datatable in my datagridview, all tab characters are removed. When the results are copied/pasted into Excel they take up one column instead of automatically breaking out. I have been using datagridview to preview results/copy to clipboard; Is there any way to retain the tabs in this view?
Expected Result: Result 1 [tab] Result 2 [tab] Result 3
Result in datatable: Result 1 [tab] Result 2 [tab] Result 3
Result in datagridview: Result 1Result 2Result 3
If the only way to achieve this is to copy directly from my datatable, I have seen a few posts on how to accomplish that. Thanks!
You have numerous options available, but in most cases you'll need to perform some looping one way or another - however even with 1000+ records it's performance hardly takes a hit.
So for the first couple of options let's assume I have the following setup - keeping with your one DataGridViewColumn idea:
Me.table = New DataTable()
Me.table.Columns.Add("Data", GetType(String))
For i As Integer = 0 To 999
Dim x As Integer = i * 4
Dim data As String = String.Format("Result {0}" & vbTab & "Result {1}" & vbTab & "Result {2}" & vbTab & "Result {3}", x + 1, x + 2, x + 3, x + 4)
Me.table.Rows.Add(data)
Next
Me.dataGridView1.AllowUserToAddRows = False
Me.dataGridView1.DataSource = Me.table
Possible Solutions
Loop through the DataTable, concatenate the data, and set the clipboard text:
Private Sub button1_Click(sender As Object, e As System.EventArgs) Handles button1.Click
Dim content As String = String.Empty
For Each row As DataRow In Me.table.Rows
content = String.Format("{0}" & vbLf & "{1}", content, row.ItemArray(0).ToString())
Next
content = content.TrimStart(ControlChars.Lf)
Clipboard.SetText(content)
End Sub
Loop through the DataGridView.Rows, concatenate the data, and set the clipboard text:
Private Sub button1_Click(sender As Object, e As System.EventArgs) Handles button1.Click
Dim content As String = String.Empty
For Each row As DataGridViewRow In Me.dataGridView1.Rows
content = String.Format("{0}" & vbLf & "{1}", content, row.Cells(0).Value.ToString())
Next
content = content.TrimStart(ControlChars.Lf)
Clipboard.SetText(content)
End Sub
And to make the grid look a little better for both option 1 and 2, since the display seems to ignore tabs:
Private Sub dataGridView1_CellFormatting(ByVal sender As Object, _
ByVal e As DataGridViewCellFormattingEventArgs) _
Handles dataGridView1.CellFormatting
Dim value As String = e.Value.ToString().Replace(vbTab, " ")
e.Value = value
End Sub
With that your grid might look like:
In addition to the original setup and instead of binding to the original DataTable, split the table's data by the tabs and display them in separate columns:
Dim splitTable As New DataTable()
For Each row As DataRow In Me.table.Rows
Dim splitItems = row.ItemArray(0).ToString().Split(ControlChars.Tab)
For i As Integer = splitTable.Columns.Count To splitItems.Length - 1
splitTable.Columns.Add(String.Empty, GetType(String))
Next
splitTable.Rows.Add(splitItems)
Next
Me.dataGridView1.AllowUserToAddRows = False
Me.dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
Me.dataGridView1.DataSource = splitTable
Then you can use the built-in clipboard method for the DataGridView:
Private Sub button1_Click(sender As Object, e As System.EventArgs) Handles button1.Click
Me.dataGridView1.SelectAll()
Clipboard.SetDataObject(Me.dataGridView1.GetClipboardContent())
End Sub
With that your grid might look like:
For all three options, clicking button1 to copy the data and hitting Ctrl+V in Excel will produce:
Note that Wrap Text will be on by default.
Pros:
Options 1 and 2 leave the user-selected cells intact. Option 3 looks better with separated DataGridView columns.
Cons:
Options 1 and 2 can look less clean pending the data. Option 3 selects all cells, losing the user's previous selected cells.

Sorted List in Array Visual Basic [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I have a program that creates a list of 25 random numbers from 0 to 1,000. I have to buttons the first button will load a list box with the random numbers and the second button will sort the list of numbers from the smallest to largest which is where I implemented bubble sort code. Now the other list box that is supposed to hold the sorted numbers doesn't work properly it only shows one number instead of all of them.
Here is my code:
Option Strict On
Public Class Form1
Dim rn As Random = New Random
Dim Clicked As Long = 0
Dim numbers, sort As Long
Private Sub GenerateBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GenerateBtn.Click
Clicked += 1
For x = 0 To 25
numbers = rn.Next(0, 1000)
RandomBox.Items.Add(numbers)
If Clicked >= 2 Then
RandomBox.Items.Clear()
Clicked = 1
End If
Next
End Sub
Private Sub SortBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SortBtn.Click
Dim Sorted() As Long = {numbers}
Dim Swapped As Boolean
Dim endOfArray As Integer = Sorted.Length - 1
Dim Tmp As Byte
While (Swapped)
Swapped = False
For I = 0 To endOfArray - 1
If Sorted(I) > Sorted(I + 1) Then
Tmp = CByte(Sorted(I))
Sorted(I) = Sorted(I + 1)
Sorted(I + 1) = Tmp
Swapped = True
End If
endOfArray = endOfArray - 1
Next
End While
SortBox.Items.Clear()
For I = 0 To Sorted.Count - 1
SortBox.Items.Add(Sorted(I))
Next
End Sub
End Class
Change your:
Dim Sorted() As Long = {numbers}
to
Sorted(x) = numbers
edit: Since you changed your code. You need to put back in the line that loads the Sorted Array.
For x = 0 To 25
numbers = rn.Next(0, 1000)
RandomBox.Items.Add(numbers)
Sorted(x) = numbers
If Clicked >= 2 Then
RandomBox.Items.Clear()
Clicked = 1
End If
Next
and remove the:
Dim Sorted() As Long = {numbers}
from the second part and put this declaration back in the beginning like you had:
Dim Sorted(26) as Long
The way you have will only show the latest random number. It is not any array but a single entity. Therefore only the latest will be add into the array. You need to load each number into the array as you create each one. Thus the (x) which loads it into position x.
You didn't use any arrays at all in your project...you're using the ListBox as your storage medium and that's a really bad practice.
I recommend you set it up like this instead:
Public Class Form1
Private rn As New Random
Private numbers(24) As Integer ' 0 to 24 = 25 length
Private Sub GenerateBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GenerateBtn.Click
For x As Integer = 0 To numbers.Length - 1
numbers(x) = rn.Next(0, 1000)
Next
' reset the listbox datasource to view the random numbers
RandomBox.DataSource = Nothing
RandomBox.DataSource = numbers
' empty out the sorted listbox
SortBox.DataSource = Nothing
End Sub
Private Sub SortBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SortBtn.Click
' make a COPY of the original array that we will sort:
Dim sorted(numbers.Length - 1) As Integer
Array.Copy(numbers, sorted, numbers.Length)
Dim Swapped As Boolean = True
Dim endOfArray As Integer = Sorted.Length - 1
Dim Tmp As Integer
While (Swapped)
Swapped = False
For I As Integer = 0 To endOfArray - 1
If sorted(I) > sorted(I + 1) Then
Tmp = sorted(I)
sorted(I) = sorted(I + 1)
sorted(I + 1) = Tmp
Swapped = True
End If
Next
endOfArray = endOfArray - 1
End While
' reset the listbox datasource to view the sorted numbers
SortBox.DataSource = Nothing
SortBox.DataSource = sorted
End Sub
End Class
Also, note that you were decrementing endOfArray inside your for loop. You should only decrement it after each pass; so outside the for loop, but inside the while loop.
Additionally, you were using a Tmp variable of type Byte, but generating numbers between 0 and 999 (inclusive). The Byte type can only hold values between 0 and 255 (inclusive).
Your Bubble Sort implementation was very close to correct!

Loop through contents in the text file

New TechGuy on this site. Thought i'd make this resourceful since im getting ready to graduate and want more programming practice. I have a question:
I tried looping through a text file I created and I wanted to replace each multiple of 3 with the word "changed". I created a text file and entered numbers 1-15 on each line. My code is below but for some reason it would only change the number 3 and 13. I tried using this link as a resource (Loop through the lines of a text file in VB.NET) but that wasnt to helpful. Anyway here is my code, can someone help with what i'm doing wrong?
Public Class numbers
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim OpenFilePrompt As New OpenFileDialog
openFilePrompt.ShowDialog()
Dim currentReader As New System.IO.StreamReader(OpenFilePrompt.FileName)
txtInput.Text = currentReader.ReadToEnd
Dim a As String
Dim numbers As New List(Of String)
a = txtInput.Text
numbers.Add(a)
Dim b As Integer
For i = 0 To numbers.Count Step 3
b = b + 3
TextBox2.Text = (numbers.Item(i).Replace(b.ToString, "Changed"))
Next
End Sub
End Class
You are setting numbers (the first item) to a, which is txtInput.Text.
Then you have a one size list which is completely useless!
You should use Mod instead.
Divides two numbers and returns only the remainder.
So just check if Integer Mod 3 equals 0.
Also consider using File.ReadAllLines(String), Val(String), String.Join(String, String()) and File.WriteAllLines(String, String()).
Dim Content() As String = File.ReadAllLines(OpenFilePrompt.FileName)
For Index As Integer = 0 To Content.Length - 1
Dim Number As Integer = Val(Content(Index))
If Number Mod 3 = 0 Then
Content(Index) = "changed"
End If
Next
txtInput.Text = String.Join(vbCrLf, Content)
File.WriteAllLines(OpenFilePrompt.FileName, Content)

Binary Search or Insertion Sort with list view [Visual Basic .net]

Recently when creating a program for my client as part of my computing project in visual basic .net I've came across a problem, which looks like following; In order to receive additional marks for my program I must take an advantage of either Binary Search or Insertion Sort subroutine declared recursively, so far the only place I can use it on is my View form which displays all reports generated by program but the problem with this is since I'm using MS Access to store my data all of the data is downloaded and placed in listview in load part of form. So the only way I can use it is by running it on listview which is a major problem for me due to the fact that I'm not very experienced in vb.
For binary search I have tried downloading all of the items in specified by user column into an array but that's the bit I was struggling on the most because I'm unable to download all items from only one column into an array. Also instead of searching every single column user specifies in my form in which column item is located (For example "19/02/2013" In Column "Date"), In my opinion if I manage to download every single entry in specified column into an array it should allow me to run binary search later on therefore completing the algorithm. Here's what I've got so far.
Sub BinarySearch(ByVal Key As String, ByVal lowindex As String, ByVal highindex As String, ByVal temp() As String)
Dim midpoint As Integer
If lowindex > highindex Then
MsgBox("Search Failed")
Else
midpoint = (highindex + lowindex) / 2
If temp(midpoint) = Key Then
MsgBox("found at location " & midpoint)
ElseIf Key < temp(midpoint) Then
Call BinarySearch(Key, lowindex, midpoint, temp)
ElseIf Key > temp(midpoint) Then
Call BinarySearch(Key, midpoint, highindex, temp)
End If
End If
End Sub
Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
Dim Key As String = txtSearch.Text
Dim TargetColumn As String = Me.lstOutput.Columns(cmbColumns.Text).Index
Dim lowindex As Integer = 0
Dim highindex As Integer = lstOutput.Items.Count - 1
'Somehow all of the items in Target column must be placed in temp array
Dim temp(Me.lstOutput.Items.Count - 1) As String
' BinarySearch(Key, lowindex, highindex, temp)
End Sub
For Insertion sort i don't even have a clue how to start, and the thing is that I have to use my own subroutine instead of calling system libraries which will do it for me.
Code which I have to use looks like following:
Private Sub InsertionSort()
Dim First As Integer = 1
Dim Last As Integer = Me.lstOutput.
Dim CurrentPtr, CurrentValue, Ptr As Integer
For CurrentPtr = First + 1 To Last
CurrentValue = A(CurrentPtr)
Ptr = CurrentPtr - 1
While A(Ptr) > CurrentValue And Ptr > 0
A(Ptr + 1) = A(Ptr)
Ptr -= 1
End While
A(Ptr + 1) = CurrentValue
Next
Timer1.Enabled = False
lblTime.Text = tick.ToString
End Sub
Any ideas on how to implement this code will be very appreciated, and please keep in my mind that I'm not very experienced in this language
Perhaps this might give you a place to begin. If you already have a ListView with "stuff" in it you could add a button to the form with the following code to copy the Text property for each item into an array:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myArray(Me.ListView1.Items.Count - 1) As String
Dim i As Integer
' load array
For i = 0 To Me.ListView1.Items.Count - 1
myArray(i) = Me.ListView1.Items(i).Text
Next
' show the results
Dim s As String = ""
For i = 0 To UBound(myArray)
s &= String.Format("myArray({0}): {1}", i, myArray(i)) & vbCrLf
Next
MsgBox(s, MsgBoxStyle.Information, "myArray Contents")
' now go ahead and manipulate the array as needed
' ...
End Sub

Display output on the form in VB 2010

I'm designing a windows form. I have output to be displayed on the form it self.
Tried using print, but it is not working.
How do I do that?
I'M NOT PRINTING THE FORM.
ADDED:
I need to display 3 numbers with text string next to each number.
I want to do this in a way that it shows in the form or label in the form without overwriting the previous results.
example:
3 (wrong) 1 (right) 8 (wrong)
2 (wrong) 1 (right) 5 (right)
9 (right) 1 (right) 5 (right)
ADDED:
Thanks for the help everyone. one more question and i think i'm good.
I was thinking of doing something like this inside a loop, problem is I can't add a string and an int together to make a new var:
Xnum1 = Xnum1 + 50
Xnum2 = Xnum1 + ".0F"
Ynum1 = Ynum1 + 50
Ynum2 = Ynum1 + ".0F"
In VB6 you could use the Print statement to draw to the surface of the form. In VB.NET, however, you should be using the Form.CreateGraphics method to create a new Graphics object that can be used to draw to the form's surface. For instance:
Private Sub PrintText(text As String, x As Single, y As Single)
Dim g As Graphics = Me.CreateGraphics()
g.DrawString(text, New Font("Arial", 16), New SolidBrush(Color.Black), New PointF(x, y))
End Sub
That would be the closest equivalent to using the VB6 Print statement like that.
However, I would strongly recommend using a control to display the data. It looks like for the data you need to display, a simple multi-line text box or label would be sufficient. For instance:
Private Sub AppendResult(index As Integer, right As Boolean)
If right Then
TextBox1.Text = TextBox1.Text & " " & index.ToString() & " (right)"
Else
TextBox1.Text = TextBox1.Text & " " & index.ToString() & " (wrong)"
End If
End Sub
If you want to get more fancy, you could look into using a data grid, a list box, a list view, or even a table layout control instead.
I believe that the most efficient way is to use a tableLayoutPanel with 6 columns. Add in each cell a label showing in the first cell the number, in the second the indicator for that number (right/wrong). Do the same for second and third number.(second number = third and fourth cell, third number =fifth and sixth cell)
For the next set of numbers you can add a new row with with labels in each cell.
I'll add some code to make my answer more professional.
First you add the tableLayoutPanel in your form. You size it as you like (make its width, long enough to handle the data)
You delete the lastRow and then you add columns (you want to have 6 columns). You edit the size of the columns to be Percentage =16.67%
Public Class Form1
Private rowIndex
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
For i = 0 To 4 Step 2
Dim val As Integer = 3
AddLabels(val, i, 0)
Next
For i = 1 To 5 Step 2
Dim val As String = "right"
AddLabels(val, i, 0)
Next
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
rowIndex = rowIndex + 1
Me.TableLayoutPanel1.RowStyles.Add(New RowStyle(SizeType.Absolute, 30))
Me.TableLayoutPanel1.Height = Me.TableLayoutPanel1.Height + 30
For i = 0 To 4 Step 2
Dim val As Integer = 3 'here you have to put your number
AddLabels(val, i, rowIndex)
Next
For i = 1 To 5 Step 2
Dim val As String = "right" 'here you have to put your indicator
AddLabels(val, i, rowIndex)
Next
End Sub
Private Sub AddLabels(ByVal lblValue As String, ByVal column As Integer, ByVal row As Integer)
Dim lblHeader As New Label
lblHeader.AutoSize = True
lblHeader.Margin = New Padding(0)
lblHeader.BackColor = Color.Transparent
lblHeader.TextAlign = ContentAlignment.MiddleLeft
lblHeader.Dock = DockStyle.None
lblHeader.Text = lblValue
'Put the lblHeader in the right cell
Dim lblHeaderPos As New TableLayoutPanelCellPosition(column, row)
TableLayoutPanel1.SetCellPosition(lblHeader, lblHeaderPos)
TableLayoutPanel1.Controls.Add(lblHeader)
End Sub
Let me know if you facing any problems.
Also if you don't know how many rows you will add, put the tableLyoutPanel inside a panel. Make the panel's property AutoScroll=True and then you can add infinite number of new rows.