Reference Form2.DataGridView from code on Form1 - vb.net

I am new to this forum. This is my first post, though I have spent a lot of time here searching for answers.
I have used VBA in Excel for many years, but have recently started using VB in Visual Studio 2015. I have created Form 1 as a MDIContainer and have another form opened inside this. This form (FormXYZ) contains a DataGridView.
Form1 has a MenuStrip and a I am currently trying to write the code, when one of these menu items is selected, to populate the DGV from a CSV. At this stage I am only trying to read the data and then I will work on the code to split the strings up.
Screenshot
I have no problem with selecting a file to import and the streamreader appears to read the file, but no data makes it to the DGV.
When I tried putting the code on FormXYZ for a button click event, the DGV was populated. So I believe the error is due to the way I am referencing the DGV, as the code for the MenuStrip_Click event is on Form1, but the DGV is on FormXYZ.
I would appreciate if somebody could point out where I am going wrong. My code is shown below.
Thanks Tepede
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim FormXYZ As New FormXYZ()
FormXYZ.MdiParent = Me 'Set the Parent Form of the Child window.
FormXYZ.Show() 'Display the XYZ form.
End Sub
'-------------------------------------
'StripMenu click command to import CSV
Public Sub TSMIFileImportCSV_Click(sender As Object, e As EventArgs) Handles TSMIFileImportCSV.Click
Dim Filename As String
Dim RowValue As String
Dim OpenFile As OpenFileDialog = New OpenFileDialog()
'Open file dialog
With OpenFile
.Filter = "CSV (*.CSV)|*.csv"
.FilterIndex = 1
.InitialDirectory = "C:\"
.Title = "Open File"
.CheckFileExists = False
End With
If OpenFile.ShowDialog() = DialogResult.OK Then
Filename = OpenFile.FileName
End If
'---------
' Read CSV file content
Dim objReader As StreamReader = New StreamReader(Filename)
While objReader.Peek() <> -1
RowValue = objReader.ReadLine()
'Fist column is Boolean, the second should have the data from the CSV file
FormXYZ.DataGridView1.Rows.Add(True, RowValue, "Test", "Test")
End While
objReader.Close()
End Sub

It looks like you are losing your instance to the FormXYZ that you displayed due to it's definition being in the Form Load. Expand the scope of that variable to be at the class level.
Public Class Form1
Private FormXYZ As FormXYZ
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FormXYZ = New FormXYZ()
FormXYZ.MdiParent = Me 'Set the Parent Form of the Child window.
FormXYZ.Show() 'Display the XYZ form.
End Sub

Related

Print-to-screen log window

I have to run a process - through the execution of a batch script - which produces an output that is saved as a text file. Furthermore, I need to see this output on a form of the application of mine and, to do this, I've set an iterative timer which updates every second the content of a non-editable RichTextBox but I have two issues:
Each time the timer stops and restarts, I need to create a copy the output file, since the file is used from another process and can't be loaded onto the software as it is;
Creating and loading this text file may be honerous in terms of hardware capability, since this file may reach really big size (even more than 5 GB).
Here is the code I'm providing:
Private Sub Form9_Load(sender As Object, e As EventArgs) Handles MyBase.Load
[...]
Me.Timer1.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds
Me.Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Application.DoEvents()
Dim p = Process.GetProcessesByName("fds2ftmi_win_64")
Dim appPath As String = Path.GetDirectoryName(Application.ExecutablePath)
If My.Computer.FileSystem.FileExists(Form1.TextBox5.Text + "/HTAoutput.dat") Then
If p.Count > 0 Then
RichTextBox1.Refresh()
My.Computer.FileSystem.CopyFile(Form1.TextBox5.Text + "/HTAoutput.dat", Form1.TextBox5.Text + "/HTAoutemp.dat", Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, FileIO.UICancelOption.DoNothing)
RichTextBox1.LoadFile(Form1.TextBox5.Text + "/HTAoutemp.dat", RichTextBoxStreamType.PlainText)
RichTextBox1.SelectionStart = RichTextBox1.TextLength
RichTextBox1.ScrollToCaret()
Else
Call Button3_Click(sender, e)
End If
End If
End Sub
Is there a more efficient way to show this stream-writing onto my log-window?
Thanks all are gonna answer me
EDIT 1:
Here is the code I'm providing:
Dim p = Process.GetProcessesByName("fds2ftmi_win_64")
Dim appPath As String = Path.GetDirectoryName(Application.ExecutablePath)
Dim str As FileStream
str = File.Open(Form1.TextBox5.Text + "/HTAoutput.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
If My.Computer.FileSystem.FileExists(Form1.TextBox5.Text + "/HTAoutput.dat") Then
If p.Count > 0 Then
RichTextBox1.LoadFile(str, RichTextBoxStreamType.PlainText)
RichTextBox1.SelectionStart = RichTextBox1.TextLength
RichTextBox1.ScrollToCaret()
Application.DoEvents()
Else
Call Button3_Click(sender, e)
End If
End If
Here is a simple demonstration of opening a file once and continuing to read only new data as it is added to that file.
Create a new WinForms Application project with two forms. Add a TextBox and a Button to each form. Make the TextBox multiline on Form1. Add a text file to your project named Test.txt and set Copy to Output Directory to Copy always. Add some default text to the file. Add this code to Form1:
Imports System.IO
Public Class Form1
Private reader As StreamReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Open the file for reading and allow sharing.
Dim filePath = Path.Combine(Application.StartupPath, "Test.txt")
Dim strm = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
reader = New StreamReader(strm)
'Read all available text and append to the existing text.
TextBox1.Text = reader.ReadToEnd()
Form2.Show()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Read all available text and append to the existing text.
TextBox1.AppendText(reader.ReadToEnd())
End Sub
End Class
and add this code to Form2:
Imports System.IO
Public Class Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim filePath = Path.Combine(Application.StartupPath, "Test.txt")
'Write a new line of text to the file.
File.AppendAllText(filePath, Environment.NewLine & TextBox1.Text)
'Get ready for the next line of text.
TextBox1.Clear()
TextBox1.Select()
End Sub
End Class
Run the project and you'll see your default text in Form1. Enter some text into Form2 and click the Button. Do that a few times. Now click the Button on Form1. Voila! Repeat that cycle and see the text you enter on one form magically appear on the other.
Now go back and examine the code more closely. You can see that Form2 appends a line of code to the file each time you click the Button. Form1 reads the initial contents of the file when it loads and displays that, but it keeps the file open. Each time you click the Button, it will read only the new data, i.e. only the data after where it previously read up to. It then appends that new text to the existing text in the TextBox.

Separate String Lines using StreamReader | VB.net

I am trying to make my own checklist app. I am using a ListView object to display each checklist item. I can add individual items to the object. I don't know how to save the ListView items on exit and then load them in on startup. (I tried using My.Settings, but it doesn't work.)
My solution was to make an import/export system using .txt files to store data. They are formatted like this:
Item1
Item2
Item3
When I import them, it all shows as one long item in ListView. I am using the code below.
Private Sub ChooseFileButton_Click(sender As Object, e As EventArgs) Handles ChooseFileButton.Click
If ImportFileDialog.ShowDialog = DialogResult.OK Then
Dim fileReader As String
fileReader =
My.Computer.FileSystem.ReadAllText(ImportFileDialog.FileName)
ImportFileDialog.RestoreDirectory = True
ChecklistObject.Items.Add(fileReader)
End If
End Sub
If anyone knows how to write individual items on their own line in a text file, that would be great too.
EDIT: Exporting doesn't work either. Using code below:
Private Sub ExportButton_Click(sender As Object, e As EventArgs) Handles ExportButton.Click
ExportFileDialog.Filter = "Keklist Save|*.kek"
If ExportFileDialog.ShowDialog = DialogResult.OK _
Then
ChecklistObject.Items.Item()
End If
End Sub
In your example code you are only adding one item to the list view so it will only show the one line.
You could use System.IO.File.ReadAllLines to read all the lines of the file into a string array.
Private Sub ChooseFileButton_Click(sender As Object, e As EventArgs) Handles ChooseFileButton.Click
If ImportFileDialog.ShowDialog = DialogResult.OK Then
Dim path As String = ImportFileDialog.FileName
Dim lines() As String = File.ReadAllLines(path)
ImportFileDialog.RestoreDirectory = True
For Each line in lines
ChecklistObject.Items.Add(line)
Next
End If
End Sub

Making a Datatable's content appear in a DataGridView

I am continuing my rewrite of an old VB6 into .Net as part of my .Net learning. I have managed to read a CSV file into a Datatable, and I can view it has populated properly using the 'datatable visualiser' when I look at 'dt', but it doesn't seem to populate the DataGridView control I am trying to tie it to. I have spent a couple of hours browsing other threads and trying things, but I cannot see what I am doing wrong. The DataGridView is on another form in the App, and I am reading the CSV file (a config file of sorts) from the main MDI form. When I show the child form containing the DataGridView it is always empty (it actually seems to have added the two datatable rows, but their content is all blank).
Public dt As New DataTable
Public ThisFilename As String = "c:\SitesDB.cfg"
Private Sub GetSitesDB()
Dim sr As New IO.StreamReader(ThisFilename)
Dim newline() As String = sr.ReadLine.Split(","c)
dt.Columns.AddRange({New DataColumn(newline(0)), New DataColumn(newline(1)), New DataColumn(newline(2)), New DataColumn(newline(3)),
New DataColumn(newline(4)), New DataColumn(newline(5)), New DataColumn(newline(6)), New DataColumn(newline(7)), New DataColumn(newline(8)),
New DataColumn(newline(9)), New DataColumn(newline(10)), New DataColumn(newline(11))})
While (Not sr.EndOfStream)
newline = sr.ReadLine.Split(","c)
Dim newrow As DataRow = dt.NewRow
newrow.ItemArray = {newline(0), newline(1), newline(2), newline(3), newline(4), newline(5), newline(6), newline(7), newline(8), newline(9), newline(10), newline(11)}
dt.Rows.Add(newrow)
End While
Form1.DataGridView1.DataSource = dt ' data can be seen here using datatable visualiser hovering over 'dt'
End Sub
Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
Form1.Show()
End Sub
I have tried refreshing the DataGridView, to no avail. I am wondering if its something to do with Form1.Show() being actioned after the datatable is tied to the DataGridView?
But the following didn't help
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' chkBit.Checked = False
' Dim cfgtext As String : cfgtext = ""
DataGridView1.DataSource = NAMS.dt
End Sub

Import CSV file to database using VB

I need to import the information from a CSV txt file to a database using the DataGridView in my form. The application should allow the user to open a .txt file and then update the DataGridView table in my form. I am able to get the file, but am unable to update the grid using the file. I can update textboxes, but cannot figure out how to update the grid. Can anyone help me out with this?
Imports Microsoft.VisualBasic.FileIO
Imports System.IO
Public Class Form1
Private fileToOpen As String 'the file to be opened and read
Private responseFileDialog As DialogResult 'response from OpenFileDialog
Private myStreamReader As StreamReader 'the reader object to get contents of file
Private myStreamWriter As StreamWriter 'the writer object to save contents of textbox
Private myTextFieldParser As TextFieldParser ' To parse text to searched.
Dim myDataAdapter As OleDb.OleDbDataAdapter
Dim myString() As String
Dim myRow As DataRow
Private Sub PeopleBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles PeopleBindingNavigatorSaveItem.Click
Me.Validate()
Me.PeopleBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.MyContactsDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MyContactsDataSet.People' table. You can move, or remove it, as needed.
Me.PeopleTableAdapter.Fill(Me.MyContactsDataSet.People)
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
Dim fileContentString As String 'contents of the file
Dim update As New OleDb.OleDbCommandBuilder(myDataAdapter)
'Dim myRow As DataRow
'set the properties of the OpenFileDialog object
OpenFileDialog1.InitialDirectory = My.Computer.FileSystem.CurrentDirectory
OpenFileDialog1.Title = "Select File to View..."
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
'responseFileDialog contains holds the response of the user (which button they selected)
responseFileDialog = OpenFileDialog1.ShowDialog()
'check to see if the user select OKAY, if not they selected CANCEL so don't open anything
If (responseFileDialog <> System.Windows.Forms.DialogResult.Cancel) Then
'make sure there isn't a file already open, if there is then close it
If (myStreamReader IsNot Nothing) Then
myStreamReader.Close()
'TextBoxFileOutput.Clear()
End If
'open the file and read its text and display in the textbox
fileToOpen = OpenFileDialog1.FileName
myStreamReader = New StreamReader(OpenFileDialog1.FileName)
initTextFieldParser()
'loop through the file reading its text and adding it to the textbox on the form
Do Until myStreamReader.Peek = -1
fileContentString = myStreamReader.ReadLine()
'Try
' myTextFieldParser = New TextFieldParser(fileToOpen)
' myTextFieldParser.TextFieldType = FieldType.Delimited
' myTextFieldParser.SetDelimiters(",")
'Catch ex As Exception
' MessageBox.Show("Cannot Open File to Be Read!")
'End Try
myTextFieldParser.TextFieldType = FieldType.Delimited
myString = TextFieldParser.NewLine()
myRow.Item("FirstName") = myString(1)
MyContactsDataSet.Tables("People").Rows.Add(myRow)
PeopleTableAdapter.Update(MyContactsDataSet)
'TextBoxFileOutput.AppendText(fileContentString)
'TextBoxFileOutput.AppendText(Environment.NewLine)
Loop
'close the StreamReader now that we are done with it
myStreamReader.Close()
'SaveToolStripMenuItem.Enabled = True
End If
End Sub
Private Sub initTextFieldParser()
'Close myTextFieldParser in case the user is surfing through the records and then
'decides to search for a particular last name --> Basically start searching from beginning of the file
If (myTextFieldParser IsNot Nothing) Then
myTextFieldParser.Close()
End If
Try
myTextFieldParser = New TextFieldParser(fileToOpen)
myTextFieldParser.TextFieldType = FieldType.Delimited
myTextFieldParser.SetDelimiters(",")
Catch ex As Exception
MessageBox.Show("Cannot Open File to Be Read!")
End Try
End Sub
End Class
updating gridview with your file content
Import System.IO as we gonna need StreamReader
Using reader As New StreamReader("filepath")
DataGridView1.Columns.Add("col1",reader.ReadToEnd())
End Using
check this out!

Visual Basic Form. How to let users save text file where they want

Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
Dim CurrentDir As String = Environment.CurrentDirectory
Dim OutputFile2 As String = IO.Path.Combine(CurrentDir, "input.txt")
IO.File.WriteAllLines(OutputFile2, Result1.Lines)
End Sub
Right now, I have coding that saves a text file in the current directory. However, I want to have a browse button for users so that they can pick where this text file is saved. How do I proceed this?
I was trying it by my self and I'm having a trouble with using save file dialog. If you can teach me how to use a save file dialog or anyway to write save browse button, I would very appreciate it!
The documentation for the SaveFileDialog object contains an example.
Here is a tutorial on how to implement SaveFileDialog using Toolbox in Visual Studio like you mentioned. The code sample is in C# but it can be easily converted to VB.
Link: www.dotnetperls.com/savefiledialog
Private Sub button1_Click(sender As Object, e As EventArgs)
' When user clicks button, show the dialog.
saveFileDialog1.ShowDialog()
End Sub
Private Sub saveFileDialog1_FileOk(sender As Object, e As CancelEventArgs)
' Get file name.
Dim name As String = saveFileDialog1.FileName
' Write to the file name selected.
' ... You can write the text from a TextBox instead of a string literal.
File.WriteAllText(name, "test")
End Sub