How to display open file name in "Save As" dialogue box with Visual Basic? - vb.net

I'm learning Visual Basic and I need to know how when I click "Save" on my GUI and the Save Dialogue box pops up, the current open file name is already being displayed in "File Name: xxxxxx"
This is what I have so far:
Imports System.IO
Public Class Form1
Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim dr As DialogResult
dr = dlgSave.ShowDialog()
If dr = Windows.Forms.DialogResult.OK Then
Dim writerVar As StreamWriter
writerVar = New StreamWriter(dlgSave.FileName, False)
writerVar.Write(txtEdit.Text)
writerVar.Close()
End If
End Sub
Cheers,
Alex

This should help you out:
' Shows the use of a SaveFileDialog to save a MemoryStream to a file.
Private Sub Button2_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles Button2.Click
' Set the properties on SaveFileDialog1 so the user is
' prompted to create the file if it doesn't exist
' or overwrite the file if it does exist.
SaveFileDialog1.CreatePrompt = True
SaveFileDialog1.OverwritePrompt = True
' Set the file name to myText.txt, set the type filter
' to text files, and set the initial directory to the
' MyDocuments folder.
SaveFileDialog1.FileName = "myText"
' DefaultExt is only used when "All files" is selected from
' the filter box and no extension is specified by the user.
SaveFileDialog1.DefaultExt = "txt"
SaveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"
SaveFileDialog1.InitialDirectory = _
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Source: https://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filename(v=vs.110).aspx
I recommend you read more into the FileName property there in order to find what you're looking for :-) hopefully that solves your problem!
Edit: Changed code to VB. Sorry, should have read the question more clearly. Been doing too much C# today..

Related

Limited Multiselect in open file dialog?

I want the user to have the option to select multiple files through openfiledialog which I have in my code, but then if the user selects a file from one folder he is then restricted to select another file only from this specific folder. What is the best way to approach to this problem?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim openfiledialog1 As New OpenFileDialog
With openfiledialog1
.Title = "Select your models"
.Filter = "Solidworks Files|*.sldprt;"
.Multiselect = True
End With
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
For Each mfile As String In openfiledialog1.FileNames
'' Add all filenames in a txt file, in a column
Next
End If
End Sub
As far as I know, OpenFileDialog doesn't offer a way to prevent the user from navigating to another directory.
One approach would be to create a class-level variable that holds the value of the recently used directory path. Then, whenever a new file is selected, you check its directory path against the one previously stored. If it matches, continue. If not, break the operation and report to the user.
Here's a complete example:
Private openFileDialog1 As New OpenFileDialog
Private modelsDirectory As String = Nothing
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
With openFileDialog1
.Title = "Select your models"
.Filter = "Solidworks Files|*.sldprt;"
.Multiselect = True
.FileName = Nothing
' Open the dialog and navigate to the previous direcoty by default.
.InitialDirectory = modelsDirectory
End With
If openFileDialog1.ShowDialog <> DialogResult.OK Then Exit Sub
Dim dirPath As String = IO.Path.GetDirectoryName(openFileDialog1.FileName)
If modelsDirectory IsNot Nothing AndAlso
Not dirPath.Equals(modelsDirectory, StringComparison.OrdinalIgnoreCase) Then
MessageBox.Show("Models must be selected from the following directory:" &
vbNewLine & modelsDirectory, "Restricted Directory")
Exit Sub
End If
' Store the value of the current directory path.
modelsDirectory = dirPath
For Each filePath As String In openFileDialog1.FileNames
' TODO: use the selected files as you see fit.
Next
End Sub
You might want to remove this restriction at some point (e.g., if you clear the list of selected files). You can achieve that by simply setting modelsDirectory to Nothing:
Private Sub ClearFilesList
' TODO: clear the files.
modelsDirectory = Nothing
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

vb..NET Pause/Resume a file copy (like windows 8 button)

Can we PAUSE and RESUME a file copy ?
Using :
3 Button_
1 OpenFileDialog_
1 FolderBrowserDialog
Imports :
Imports System.IO
Code :
Private Sub BTN_filedialog_Click(sender As Object, e As EventArgs) Handles BTN_filedialog.Click
OpenFileDialog1.InitialDirectory = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" 'Cette clé de registre ouvre "Ordinateur"
OpenFileDialog1.Title =
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = _
"All files (*.*)|*.*|txt files (*.txt)|*.txt"
Dim dlgResult = OpenFileDialog1.ShowDialog()
If dlgResult <> System.Windows.Forms.DialogResult.OK Then
MessageBox.Show("File Error " & dlgResult)
End If
End Sub
Private Sub BTN_folderbrowserdialog_Click(sender As Object, e As EventArgs) Handles BTN_folderbrowserdialog.Click
Dim dlgResult = FolderBrowserDialog1.ShowDialog()
If dlgResult <> System.Windows.Forms.DialogResult.OK Then
MessageBox.Show("Folder Error " & dlgResult)
End If
End Sub
Private Sub BTN_copyfile_Click(sender As Object, e As EventArgs) Handles BTN_copyfile.Click
My.Computer.FileSystem.CopyFile( _
OpenFileDialog1.FileName, _
FolderBrowserDialog1.SelectedPath & "\" & _
OpenFileDialog1.SafeFileName, _
FileIO.UIOption.AllDialogs)
End Sub
I use My.Computer.FileSystem.CopyFile
With Windows 8, inside the dialog box "copy", there is a pause button.
How to call this "event" ?
I do not know if this is possible, but can we send parameters to a certain Lib /. Dll to simulate the action of pressing the pause button ?
Ps : Sorry for my bad english, i'm french.
The best way to approach this would be to ignore the FileSystem.CopyFile command completely. Instead, use a FileStream to open the file you wish to copy, read the bytes, create a new file to the target destination, and write the bytes to that location.
You can read and write the file in smaller chunks so that you can check to see if a pause variable is set to true. For example, if you create a pause button, set a global variable "bCopyPaused = true". In the custom copy function you can use a simple if statement and check if bCopyPaused == true and pause the operation. You'll need to keep track of the last copied or written bytes to allow the operation to be resumed.
Here's some examples of using FileStream: http://vb.net-informations.com/files/vb.net_FileStream.htm

VB.NET - How to Drag a File From Outlook 2010 to My Form?

I'm developing an application to read XML files, get its data and populate some field. SO, I've implemented two ways to get the file: through a command button and through the drag and drop form event. Everything is OK if I use a file stored in a folder in my computer. I can drag the file, the cursor changes its appearance to the copy effect etc. However, when I try doing it dragging a file as an attachment of Outlook (my version is the 2010), I see that the cursor assumes the forbidden effect and the file is not read.
Please, see below the implementation I did, which is working only for files stored in a folder in my computer. I would like to know what more I have to implement to allow drag a file from Outlook.
Thank you in advance.
Private Sub FrmJIG_DragDrop(sender As Object, e As DragEventArgs) _
Handles Me.DragDrop
Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
Dim filestype() As String
filestype = e.Data.GetData(DataFormats.FileDrop)
Dim sReader As New StreamReader(filestype(0))
'get the filename from the file without the path
Dim file_name As String = Path.GetFileName(filestype(0))
'check the extension of the file
If Path.GetExtension(filestype(0)).ToLower() = ".xml" Then
'Read the xml file
For Each path In files
ReadXMLFile(path)
Next
Else
'warning about the file type
MessageBox.Show("Only XML files are supported!", "Warning!", _
MessageBoxButtons.OK, _
MessageBoxIcon.Warning)
End If
End Sub
Private Sub FrmJIG_DragEnter(sender As Object, e As DragEventArgs) _
Handles Me.DragEnter
'change the cursor type to drag and drop type
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
e.Effect = DragDropEffects.Copy
End If
End Sub
Please try with
Private Sub FrmJIG_DragEnter(sender As Object, e As DragEventArgs) _
Handles Me.DragEnter
'change the cursor type to drag and drop type
If e.Data.GetDataPresent(DataFormats.FileDrop) or e.Data.GetDataPresent("FileGroupDescriptor") Then
e.Effect = DragDropEffects.Copy
End If
End Sub