Read .txt file and display into different button - vb.net

I'm trying to display some text on my button but I can only display those text on 1 button. My buttons are separated like Button1.Text, Button2.Text, and Button3.Text and my .txt file can only be displayed in Button1.Text. Here is the code that I did so far.
Private Sub FormMenu_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim R As New IO.StreamReader("TestFile.txt")
Button1.Text = R.ReadToEnd()
R.Close()
End Sub
Inside my .txt file got something like
First Button
Second Button
Third Button
and I want my system be able to read them and display into each of the button. How to do that? Thank you.

Use something like...
Private Sub FormMenu_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim lines() As String = System.IO.File.ReadAllLines("TestFile.txt")
For i As Integer = 1 To lines.Length
Dim ctl As Control = Me.Controls.Find("Button" & i, True).FirstOrDefault
If Not IsNothing(ctl) Then
ctl.Text = lines(i - 1)
End If
Next
End Sub

Private Sub FormMenu_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim R As New IO.StreamReader("TestFile.txt")
Dim words As String() = R.ReadToEnd().Split(New String() {Environment.NewLine})
Button1.Text = words(0)
Button2.Text = words(1)
Button3.Text = words(2)
R.Close()
End Sub

Related

if the file not exits then return no error vb

I have start this application every things its work fine but i have a small bug but i can not find the solution to solve the error.
i have debug it and the error its because the file not exist
is there any way to me to populate my datagridview with all *.gif images From a directory and the check if its null or some thing like that.
What i mean is is there any way to my to populate all gif images found on the chose Directory?
in fact i have all ready try like this but i get one error "Provided column already belongs to the DataGridView control.
Well finaly i have found a solution to load all images from a directory to a datagridview programmatic
Here Is The Working Code
Public Class Form5
Private Sub addBtn_Click(sender As Object, e As EventArgs) Handles addBtn.Click
'Populate()
ShowImages()
End Sub
'CLEAR DATAGRIDVIEW
Private Sub clearBtn_Click(sender As Object, e As EventArgs) Handles clearBtn.Click
DataGridView1.Rows.Clear()
End Sub
'WHEN AN IMAGE IS CLICKED
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
MessageBox.Show("You Clicked Image At Col: " + e.ColumnIndex.ToString() + " Row: " + e.RowIndex.ToString())
End Sub
Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Public Sub ShowImages()
Dim directory As New System.IO.DirectoryInfo("C:\avitogifconverter\")
If directory.Exists Then
Dim pngFiles() As System.IO.FileInfo = directory.GetFiles("*.gif")
For Each pngFile As System.IO.FileInfo In pngFiles
If pngFile.Exists Then
Dim image = System.Drawing.Image.FromFile(pngFile.FullName)
Using image
Dim count = 1
' do something with the image like show in picture box
'CONSTRUCT IMG COLUMN
Dim imgCol As DataGridViewImageColumn = New DataGridViewImageColumn()
imgCol.HeaderText = "Photo"
imgCol.Name = "Col 1"
DataGridView1.Columns.Add(imgCol)
'CONSTRUCT ROWS
'FIRST ROW
Dim img As Image = System.Drawing.Image.FromFile(pngFile.FullName)
Dim row As Object() = New Object() {img, img, img}
DataGridView1.Rows.Add(row)
End Using
End If
Next
End If
End Sub
End Class
Using Directory.EnumerateFiles, you could do something like this:
Dim row = New List(Of Image)(3)
For Each filename In Directory.EnumerateFiles("C:\avitogifconverter", "*.gif")
row.Add(Image.FromFile(filename))
If row.Count = 3 Then
DataGridView1.Rows.Add(row.ToArray())
row.Clear()
End If
Next
If row.Count > 0 Then
DataGridView1.Rows.Add(row.ToArray())
row.Clear()
End If

VB.NET Read .Txt File Into Multiple Text Boxes

I have a program that I can enter in names and integer values in the text boxes and then save those to a file. That works perfectly fine but the part I need help with is the reading of the file.
The data is saved into the file much like a csv file. example:
Test, 5, 5, 5
dadea, 5, 5, 5
das, 5, 5, 5
asd, 5, 5, 5
dsadasd, 5, 5, 5
My problem is, how do I read that into multiple text boxes on my form?
The names (first value of each row) should go into their corresponding Name textbox (i.e. txtName0, txtName1, txtName2, etc.) and the integer values should also go into their corresponding text boxes (txtCut1, txtColour1, etc.).
I have spent the past 2 hours trying to figure this out but I just cant.
The part I need help with is the last method.
Imports System.IO
Public Class Form1
Private aPricesGrid(,) As TextBox
Private aAverages() As TextBox
Private aNames() As TextBox
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
aPricesGrid = {{txtCut1, txtColour1, txtUpDo1, txtHighlight1, txtExtensions1},
{txtCut2, txtColour2, txtUpDo2, txtHighlight2, txtExtensions2},
{txtCut3, txtColour3, txtUpDo3, txtHighlight3, txtExtensions3},
{txtCut4, txtColour4, txtUpDo4, txtBHighlight4, txtExtensions4},
{txtCut5, txtColour5, txtUpDo5, txtHighlight5, txtExtensions5}}
aAverages = {txtAvg0, txtAvg1, txtAvg2, txtAvg3, txtAvg4}
aNames = {txtName0, txtName1, txtName2, txtName3, txtName4}
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
For nCol As Integer = 0 To 4
Dim nColTotal As Integer = 0
Dim nColItems As Integer = 0
For nRow As Integer = 0 To 2
Try
nColTotal += aPricesGrid(nRow, nCol).Text
nColItems += 1
Catch ex As Exception
End Try
Next
aAverages(nCol).Text = (nColTotal / nColItems).ToString("c")
Next
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
For Each txt As Control In Me.Controls
If TypeOf txt Is TextBox Then
txt.Text = String.Empty
End If
Next
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Dim oSaveFileDialog As New SaveFileDialog()
'Display the Common file Dialopg to user
oSaveFileDialog.Filter = "Text Files (*.txt)|*.txt"
If oSaveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
' Retrieve Name and open it
Dim fileName As String = oSaveFileDialog.FileName
Dim outputFile As StreamWriter = File.CreateText(fileName)
For nRow As Integer = 0 To 4
outputFile.Write(aNames(nRow).Text)
For nCol As Integer = 0 To 2
outputFile.Write(", " & aPricesGrid(nRow, nCol).Text)
Next
outputFile.WriteLine()
Next
outputFile.Close()
End If
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub ReadToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ReadToolStripMenuItem.Click
Dim oOpenFileDialog As New OpenFileDialog()
'Display the Common file Dialopg to user
oOpenFileDialog.Filter = "Text Files (*.txt)|*.txt"
If oOpenFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim fileName As String = oOpenFileDialog.FileName
Dim OpenFile As StreamReader = File.OpenText(fileName)
End If
End Sub
End Class
Try this method.
Dim mindex as integer
Dim string1 as string()
Dim OpenFile As StreamReader = File.OpenText(fileName)
While OpenFile .Peek <> -1
string1= OpenFile .ReadLine.Split(",")
If mindex = 0 Then
txtname1.text=string1(0)
txtcut1.text=string1(1)
txtcolour1.text=string1(2)
'add other textboxes
ElseIf mindex = 1 Then
txtname2.text=string1(0)
txtcut2.text=string1(1)
txtcolour2.text=string1(2)
'add other textboxes
ElseIf mindex = 2 Then
txtname3.text=string1(0)
txtcut3.text=string1(1)
txtcolour3.text=string1(2)
'add other textboxes
ElseIf mindex = 3 Then
'your code
ElseIf mindex = 4 Then
'your code
End If
mindex += 1
End While
OpenFile .Close()
hope this helps.

Is there a way in VB.NET to have buttons and menu bars that are built in the code show up in the design view?

Is there a way in VB.NET to make components like buttons and menus bars show in design view of you added them in programmatically?
I now in Java i you add a button in the code it will show in design view if you switch back and forth. Can this be done in VB.NET.
Code:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'defining the main menu bar
Dim mnuBar As New MainMenu()
'defining the menu items for the main menu bar
Dim myMenuItemFile As New MenuItem("&File")
Dim myMenuItemEdit As New MenuItem("&Edit")
Dim myMenuItemView As New MenuItem("&View")
Dim myMenuItemProject As New MenuItem("&Project")
'adding the menu items to the main menu bar
mnuBar.MenuItems.Add(myMenuItemFile)
mnuBar.MenuItems.Add(myMenuItemEdit)
mnuBar.MenuItems.Add(myMenuItemView)
mnuBar.MenuItems.Add(myMenuItemProject)
' defining some sub menus
Dim myMenuItemNew As New MenuItem("&New")
Dim myMenuItemOpen As New MenuItem("&Open")
Dim myMenuItemSave As New MenuItem("&Save")
'add sub menus to the File menu
myMenuItemFile.MenuItems.Add(myMenuItemNew)
myMenuItemFile.MenuItems.Add(myMenuItemOpen)
myMenuItemFile.MenuItems.Add(myMenuItemSave)
'add the main menu to the form
Me.Menu = mnuBar
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
'create a new TreeView
Dim TreeView1 As TreeView
TreeView1 = New TreeView()
TreeView1.Location = New Point(5, 30)
TreeView1.Size = New Size(150, 150)
Me.Controls.Add(TreeView1)
TreeView1.Nodes.Clear()
'Creating the root node
Dim root = New TreeNode("Application")
TreeView1.Nodes.Add(root)
TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 1"))
'Creating child nodes under the first child
For loopindex As Integer = 1 To 4
TreeView1.Nodes(0).Nodes(0).Nodes.Add(New _
TreeNode("Sub Project" & Str(loopindex)))
Next loopindex
' creating child nodes under the root
TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 6"))
'creating child nodes under the created child node
For loopindex As Integer = 1 To 3
TreeView1.Nodes(0).Nodes(1).Nodes.Add(New _
TreeNode("Project File" & Str(loopindex)))
Next loopindex
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
Private Sub openInWeb()
Try
Dim url As String = "http://www.stackoverflow.com"
Process.Start(url)
Catch ex As Exception
MsgBox("There's something wrong!")
Finally
End Try
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim fileReader As System.IO.StreamReader
fileReader =
My.Computer.FileSystem.OpenTextFileReader("C:\Users\itpr13266\Desktop\Asnreiu3.txt")
Dim stringReader As String
stringReader = fileReader.ReadLine()
MsgBox("The first line of the file is " & stringReader)
openInWeb()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim myStream As Stream = Nothing
Dim openFileBox As New OpenFileDialog()
openFileBox.InitialDirectory = "c:\"
openFileBox.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
openFileBox.FilterIndex = 2
openFileBox.RestoreDirectory = True
If openFileBox.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileBox.OpenFile()
If (myStream IsNot Nothing) Then
' Insert code to read the stream here.
'**************************
' your code will go here *
'**************************
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
myStream = saveFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
' Code to write the stream goes here.
myStream.Close()
End If
End If
End Sub
Private Sub ToolTip1_Popup(sender As System.Object, e As System.Windows.Forms.PopupEventArgs) Handles ToolTip1.Popup
End Sub
Private Sub Button(p1 As Object)
Throw New NotImplementedException
End Sub
Private Function myButton() As Windows.Forms.Button
Throw New NotImplementedException
End Function
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
AboutBox1.Show()
End Sub
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
Dim lbl As New Label
lbl.Size = New System.Drawing.Size(159, 23) 'set your size (if required)
lbl.Location = New System.Drawing.Point(12, 190) 'set your location
lbl.Text = "You just clicked button 5" 'set the text for your label
Me.Controls.Add(lbl) 'add your new control to your forms control collection
End Sub
Public Sub HellowWorld()
MsgBox("Hello World!")
End Sub
Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles Button6.Click
HellowWorld()
End Sub
Private Sub Button7_Click(sender As System.Object, e As System.EventArgs) Handles Button7.Click
Dim ProgressBar1 As ProgressBar
Dim ProgressBar2 As ProgressBar
ProgressBar1 = New ProgressBar()
ProgressBar2 = New ProgressBar()
'set position
ProgressBar1.Location = New Point(10, 200)
ProgressBar2.Location = New Point(10, 250)
'set values
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 200
ProgressBar1.Value = 130
ProgressBar2.Minimum = 0
ProgressBar2.Maximum = 100
ProgressBar2.Value = 40
'add the progress bar to the form
Me.Controls.Add(ProgressBar1)
Me.Controls.Add(ProgressBar2)
' Set the caption bar text of the form.
End Sub
End Class
The Designer does only show Controls that are created in the FormName.Designer.vb file. It does not run code in the FormName.vb file. When adding controls in the Designer, they are added to the InitializeComponent() method in the FormName.Designer.vb file.
So the only way to show the controls in the Designer is to add them in the Designer or to edit the FormName.Designer.vb file manually. If you decide for the latter, you should mimic the code that is generated by the Designer very closely in order to avoid problems when the Designer is shown. Also, be prepared that the Designer regards the FormName.Designer.vb file as completely generated code and might decide to recreate the file sooner or later omitting parts that it cannot handle.
Side note: in order to see the FormName.Designer.vb file, you should select "Show All Files" for the project in Solution Explorer.

For Each Item in ListBox1 do something then add item to listbox2 vb

I made an app to convert certain numbers to other format
i.e
1 = A
2 = B
3 = C
4 = D
5 = E
ETC
I have made that function with no problem and I have been using it for quite sometime, but now I would like to do things faster and in a batch.
So it's really difficult for me to copy from a text file to my Textbox1 then press button1 then copy textbox2 to other text file.
So I was thinking in loading the text file into a List Box then do a loop for each item in that list into a second list that I can export to another text file.
The importing and exporting I have it covered but where I'm stuck at is to make the loop.
Here's what I have please if you know a better way to do it let me know or tell me how to fix it this way.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using FD As New OpenFileDialog()
FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
ListBox1.Items.Clear()
ListBox1.Items.AddRange(IO.File.ReadAllLines(FD.FileName))
End If
End Using
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Do
Dim Item As String = ""
For Each i As String In ListBox1.Items
Item &= i
TextBox1.Text = Item
TextBox2.Text = MYFUNCTION(TextBox1.Text)
ListBox2.Items.Add(TextBox2.Text)
TextBox1.Text = ""
TextBox2.Text = ""
Next
Loop Until TextBox1.Text = "END"
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
'TextBox2.Text = MeidHexToDec(TextBox1.Text)
Using FD As New SaveFileDialog()
FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim FileContent As String = ""
For Each i As String In ListBox2.Items
FileContent &= i & vbCrLf
Next
IO.File.WriteAllText(FD.FileName, FileContent)
End If
End Using
End Sub
So my final aim is to do something like this:
TextFile1.txt
1
2
5
5
1
3
2
END
then after the conversion output
TextFile2.txt
A
B
E
E
A
C
B
The text file size will vary sometimes it will have only 10 items sometimes will be 50...
Thanks.
You do not need the Do loop at all and you can simplify the rest of your loop logic, like this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each i As String In ListBox1.Items
ListBox2.Items.Add(MYFUNCTION(i))
Next
End Sub
You do not need to look out for the END marker, because everything in the file was read into the ListBox1.Items collection, thus once you have looped through all of the string values in ListBox1.Items, then you are at the end of the file.
The MYFUNCTION logic returns the transformation from number to letter, thus just add the result of that function into ListBox2.Items and you are done.
Public Function Letr(N As Int16) As String
Letr = Chr(N + 64)
End Function

Is there any way for Retrieve Record Value from Table Column , Loop and Loop in vb.net

Sorry for my poor English
When the user clicks the Start button, I am trying to display all of the records from the Phone column in the Textbox1 control. I want to see all those records pass into Textbox1 While it is processing the For loop. But it is currently processing very fast so that I only see the last record in Textbox1. What i'm going wrong?
While it is processing the For loop, I change the Start button to a Stop button. So when I click the button and it currently has a Text value equal to "Stop", I want it to skip the For loop and pass the value from TextBox1 to my FirstWin. And then it should change the BtnStart.Text back to "Start"
Here's my code:
Public Class PhoneFortune
Dim CN As OleDbConnection
Dim CM As OleDbCommand
Dim DA As OleDbDataAdapter
Dim DT As New DataTable
Private Sub BtnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click
If BtnStart.Text = "Start" Then
CM = New OleDbCommand("SELECT * FROM TblPhoneNumber", CN)
DA = New OleDbDataAdapter(CM)
DA.Fill(DT)
For i = 0 To DT.Rows.Count - 1
TextBox1.Text = DT.Rows(i)("Phone")
Next
BtnStart.Text = "Stop"
End If
If BtnStart.Text = "Stop" Then
If FirstWin.Text = "" Then
FirstWin.Text = TextBox1.Text
BtnStart.Text = "Start"
ElseIf SecondWin.Text = "" Then
SecondWin.Text = TextBox1.Text
BtnStart.Text = "Start"
ElseIf ThirdWin.Text = "" Then
ThirdWin.Text = TextBox1.Text
BtnStart.Text = "Start"
End If
End If
End Sub
Private Sub PhoneFortune_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
CN = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=database\db.accdb;Jet OLEDB:Database Password=12345;")
CN.Open()
End Sub
End Class
I hope we are on the same page but if u want to slow down the process for a bit u use these two lines of code within the FOR loop
System.Threading.Thread.Sleep(1000)
Me.Refresh() Where 1000 is one second(value is represented in milliseconds).
Now what is that FirstWin.Text="" etc used for? Are you trying to start the looping,then change the text to "stop" so that when the user clicks stops it stops at the current record? Go to youtube and look for multithreading videos,not sure how to help u on that one hope the rest helps. If this is useful please acknowledge
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If Button1.Text = "Start" Then
If TextBox1.Text = "" Then
t1 = New Thread(AddressOf Me.PhoneThread)
t1.Start()
Button1.Text = "Stop"
Else
t1.Resume()
Button1.Text = "Stop"
End If
Else 'Click Stop
t1.Suspend()
Button1.Text = "Start"
If FirstWin.Text = "" Then
FirstWin.Text = TextBox1.Text
ElseIf SecondWin.Text = "" Then
SecondWin.Text = TextBox1.Text
ElseIf ThirdWin.Text = "" Then
ThirdWin.Text = TextBox1.Text
End If
End If
End Sub
Sub PhoneThread()
'Dim ThreadsArray As List(Of Threading.Thread) = New List(Of Threading.Thread)
Dim s As Integer
'MsgBox(DT.Rows.Count)
For s = 0 To DT.Rows.Count
If s = DT.Rows.Count Then
s = 0
Else
TextBox1.Text = DT.Rows(s)("Phone")
' ThreadsArray.Add(t1)
Thread.Sleep(19)
'TextBox1.Text = s.ToString()
Me.Refresh()
End If
Next
End Sub
Private Sub BtnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click
Me.Close()
End Sub
For something simple like this, System.Threading.Thread.Sleep(100) (to block the thread) followed by Application.DoEvents() (to process any button clicks) seems like it would do the trick.
For something more complicated, this approach will result in re-entrancy and difficult-to-reproduce bugs; in that case, you definitely need asynchronous programming.