Im cant get a doc from my documents to display - vb.net

Imports System.IO
Public Class Form1
Private Sub MenuItem1_Click(sender As Object, e As EventArgs) Handles MenuItem1.Click
Me.txtFileContent.Text = Nothing
End Sub
Private Sub MenuItem2_Click(sender As Object, e As EventArgs) Handles MenuItem2.Click
Me.txtFileContent.Text = Nothing
End Sub
Private Sub MenuItem3_Click(sender As Object, e As EventArgs) Handles MenuItem3.Click
Me.savSaveFile.ShowDialog()
Dim strFileName As String = Me.savSaveFile.FileName
Dim fs As New FileStream(strFileName, FileMode.Create, FileAccess.Write)
Dim TextFile As New StreamWriter(fs)
TextFile.Write(Me.txtFileContent.Text)
TextFile.Close()
fs.Close()
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MenuItem5.Click
Me.savSaveFile.ShowDialog()
Dim strFileName As String = Me.savSaveFile.FileName
Dim fs As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
Dim TextFile As New StreamWriter(fs)
TextFile.Close()
fs.Close()
End Sub
End Class
What im trying to do is display a "open" document dialog box so the text inside the box can be displayed into the text box. I did the same with the "save" document dialog box and it worked fine just confused on the Open part. Thanks a million everyone.

There are two different kind of dialog box for selecting files.
One for save operations and one for opening files.
Your code seems to use the same one and from the name I think it is a SaveFileDialog.
To open a file you need a OpenFileDialog and use a StreamReader not a StreamWriter
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MenuItem5.Click
' Create an OpenFileDialog here, for more precise property settings see the link above'
Dim openDlg = New OpenFileDialog()
' If user presses OK'
if openDlg.ShowDialog() = DialogResult.OK Then
' Still the filename selected could be empty, need to check'
Dim strFileName As String = openDlg.FileName
if strFileName.Trim().Length > 0 then
' Open the file using a reader, not a writer'
Using fs = New FileStream(strFileName, FileMode.Open, FileAccess.Read)
Using TextFile = New StreamReader(fs)
' Read everything (caution this should be used only for small files)'
Dim fileContent = TextFile.ReadToEnd
' Pass everything into a TextBox control for display'
Me.txtFileContent.Text = fileContent
End Using
End Using
End If
End If
End Sub

Related

How to save data within the Application?

I'm creating a basic To-do program. I want to save the list of tasks the user creates. Now I've tried with saving them as text files but I don't want it that way. I want it so that I can save the tasks the user creates within the program rather than external text files and then retrieve those saved files and display them in a text file.
Essentially I need a way to save data without needing to rely on databases.
A good example is GeeTeeDee. It seems to be saving its files and data etc. in the program within rather than external text file.(I'm assuming this because I can't seem find them. I could be wrong)
Update
I was doing a bit of searching can came across this: Click here!!!
But the problem is that I'm confused as to how this works. Is someone able to clear things for me? It would be GREATLY appreciated as it's exactly what I'm looking for.
The "code project" example saves the data at an external file with extension [*.brd] .
You can Use XmlSerializer to save and load your data from external xml file with extension xml,brd or anything else.
Try the code below, add into a form1 three buttons (Button1,Button2,Button3) and a DataGridView1, paste the code and Run.
press button "add data dynamically" or/and add,edit,delete row directlly from DataGridView1.
press Save data.
close and run programm
press Load data.
Imports System.Xml.Serialization
Imports System.IO
Class Form1
Dim ds As DataSet
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Button1.Text = "Load Data"
Button2.Text = "add data dynamically"
Button3.Text = "Save Data"
'Create Dataset
ds = CreateDataset()
'Set DataGridView1
DataGridView1.DataSource = ds.Tables("Person")
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
LoadFromXMLfile("c:\temp\persons.xml")
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
AddDataToDataSetDynamically(ds)
End Sub
Private Sub Button3_Click_1(sender As System.Object, e As System.EventArgs) Handles Button3.Click
SaveToXMLFile("c:\temp\persons.xml", ds)
End Sub
Private Function CreateDataset() As DataSet
Dim dataset1 As New DataSet("Persons")
Dim table1 As New DataTable("Person")
table1.Columns.Add("Id")
table1.Columns.Add("FName")
table1.Columns.Add("Age")
'...
dataset1.Tables.Add(table1)
Return dataset1
End Function
Private Sub AddDataToDataSetDynamically(d As DataSet)
d.Tables("Person").Rows.Add(1, "Andrew", "46")
d.Tables("Person").Rows.Add(2, "Nicky", "43")
d.Tables("Person").Rows.Add(3, "Helen", "15")
End Sub
Private Sub SaveToXMLFile(filename As String, d As DataSet)
Dim ser As XmlSerializer = New XmlSerializer(GetType(DataSet))
Dim writer As TextWriter = New StreamWriter(filename)
ser.Serialize(writer, d)
writer.Close()
End Sub
Private Sub LoadFromXMLfile(filename As String)
If System.IO.File.Exists(filename) Then
Dim xmlSerializer As XmlSerializer = New XmlSerializer(ds.GetType)
Dim readStream As FileStream = New FileStream(filename, FileMode.Open)
ds = CType(xmlSerializer.Deserialize(readStream), DataSet)
readStream.Close()
DataGridView1.DataSource = ds.Tables("Person")
Else
MsgBox("file not found! add data and press save button first.", MsgBoxStyle.Exclamation, "")
End If
End Sub
End Class
add that code to form1 and get the data to a textbox (add button4,textbox1)
Private Function PrintRows(dataSet As DataSet) As String
Dim s As String = ""
Dim thisTable As DataTable
For Each thisTable In dataSet.Tables
Dim row As DataRow
For Each row In thisTable.Rows
Dim column As DataColumn
For Each column In thisTable.Columns
s &= row(column) & " "
Next column
s &= vbCrLf
Next row
Next thisTable
Return s
End Function
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
TextBox1.Text = PrintRows(ds)
End Sub

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.

Unknown error wont open from computer. Basic

Sub ShowFileContents(ByVal strFileName As String)
Dim fs As New FileStream(strFileName, FileMode.Open, FileAccess.Read)
Dim TextFile As New StreamReader(fs)
Me.txtFileContents.Text = Nothing
Dim strLineOfText As String
Do While TextFile.Peek > -1
strLineOfText = TextFile.ReadLine()
Me.txtFileContents.Text = Me.txtFileContents.Text & strLineOfText & vbCrLf
Loop
TextFile.Close()
fs.Close()
End Sub
Why cant I open a file when I run program all it says is "Save" or "Cancel"
Why cant I open a file when I run program all it says is "Save" or "Cancel" What Im trying to do is open a file from my documents and display it in the textbox below. I have the save file working but not the open file
It looks like you could benefit from using the OpenFileDialog control rather than a textbox to get the file path you want to open.
Here's an example:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim ofp As New OpenFileDialog
If ofp.ShowDialog = Windows.Forms.DialogResult.OK Then
ShowFileContents(ofp.FileName)
End If
End Sub
Sub ShowFileContents(ByVal strFileName As String)
Dim TextFile As New StreamReader(strFileName)
txtFileContents.Text = Nothing
Do While Not TextFile.EndOfStream
txtFileContents.AppendText(TextFile.ReadLine() & vbCrLf)
Loop
TextFile.Close()
End Sub

Open Excel Workbook from ComboBox (VB.NET)

How to open an excel workbook from combobox?
I am using following code to populate combobox with excel filenames,
Dim files() As String
files = Directory.GetFiles("C:\Files\Folder", "*.xlsx", SearchOption.AllDirectories)
For Each FileName As String In files
ComboBox1.Items.Add(FileName.Substring(FileName.LastIndexOf("\") + 1, FileName.Length - FileName.LastIndexOf("\") - 1))
Next
But I do not have any idea about how to open the selected file.
Imports System
Imports System.IO
Imports System.Collections
Public Class Form1
Private Const TargetDir = "C:\Files\Folder"
Private FullFileList As List(Of String)
Private Sub ProcessFile(ByVal fn As String)
If Path.GetExtension(fn).ToLower = ".xlsx" Then
FullFileList.Add(fn)
ComboBox1.Items.Add(Path.GetFileName(fn))
End If
End Sub
Private Sub ProcessDirectory(ByVal targetDirectory As String)
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
Dim fileName As String
For Each fileName In fileEntries
ProcessFile(fileName)
Next fileName
Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
Dim subdirectory As String
For Each subdirectory In subdirectoryEntries
ProcessDirectory(subdirectory)
Next subdirectory
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
FullFileList = New List(Of String)
ProcessDirectory(TargetDir)
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If ComboBox1.SelectedIndex >= 0 Then
Dim prc As New System.Diagnostics.Process
Dim psi As New System.Diagnostics.ProcessStartInfo(FullFileList(ComboBox1.SelectedIndex))
psi.UseShellExecute = True
psi.WindowStyle = ProcessWindowStyle.Normal
prc.StartInfo = psi
prc.Start()
End If
End Sub
End Class
You'll need to handle an event to react to the user's selection: either a change to the selection in the ComboBox or (better) a Button click. In your event handler you can retrieve the filename from the ComboBox:
string filename = ComboBox1.SelectedItem.ToString()
Once you have the filename, you can open the file, although how you do this will depend on what you want to do with it. This answer has some information on opening Excel files in VB.NET.
Try using
Process.start("excel "+ComboBox1.SelectedItem.ToString());
on buttonclick event

Listview items and saving them as .csv

I'm doing this project where I need to save the names of the items from a listview to a .csv
Imports System.IO
Public Class cv7import
Private Sub cv7import_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim caminho As String
caminho = "C:\Documents and Settings\Software\Ambiente de trabalho\cv7import"
Dim returnValue As String()
returnValue = Environment.GetCommandLineArgs()
If returnValue.Length > 1 Then
MessageBox.Show(returnValue(1).ToString())
Else
MessageBox.Show("Nothing")
End If
' Set ListView Properties
lstvicon.View = View.Details
lstvicon.GridLines = False
lstvicon.FullRowSelect = True
lstvicon.HideSelection = False
lstvicon.MultiSelect = True
' Create Columns Headers
lstvicon.Columns.Add("Nome")
lstvicon.Columns.Add("Extensão")
lstvicon.Columns.Add("Tamanho")
lstvicon.Columns.Add("Data Modificação")
Dim DI As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(caminho)
Dim files() As System.IO.FileInfo = DI.GetFiles
Dim file As System.IO.FileInfo
Dim li As ListViewItem
For Each file In files
li = lstvicon.Items.Add(file.Name)
li.SubItems.Add(file.Extension)
li.SubItems.Add(file.Length)
li.SubItems.Add(file.LastWriteTimeUtc)
'li.SubItems.Add(FileDialog)
Next
End Sub
Private Sub btnimp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnimp.Click
' Creates a csv File
Dim csv As New System.IO.StreamWriter("C:\Documents and Settings\Software\Ambiente de trabalho\cv7import\teste.csv", True)
lstvicon.SelectedItems.CopyTo(csv)
csv.Close()
End Sub
End Class
That's what I got but I can't seem to get it to write on the .txt.
I have no idea where to go from here and i've been going around this for hours, so any help would be apreciated.
I think that you want something like this:
' Creates a csv File
Using csv As New System.IO.StreamWriter("C:\Documents and Settings\Software\Ambiente de trabalho\cv7import\teste.csv", True)
For Each oItem As ListViewItem In ListView1.Items
csv.WriteLine(String.Format("""{0}"",""{1}"",{2},{3}", oItem.Text, oItem.SubItems(0).Text, oItem.SubItems(1).Text, oItem.SubItems(2).Text )
Next
End Using
You will probably need to clean up the csv formatting, but this should give you an idea.