Use SUB variable in other sub - vb.net

I have a Open File button that opens an INI file.
Now I would like to use the path of the file so I can click a Save Button and the file is saved.
This is the code for the Open Button:
Private Sub OpenINIButton_Click(sender As Object, e As EventArgs) Handles OpenINIButton.Click
Dim OpenDLG As New OpenFileDialog
OpenDLG.Filter = "Configuration File (*.ini)|*.ini"
OpenDLG.Title = "Open INI File"
OpenDLG.InitialDirectory = "C:\"
OpenDLG.RestoreDirectory = True
DialogResult = OpenDLG.ShowDialog
If DialogResult = Windows.Forms.DialogResult.OK Then
Dim OpenFile = OpenDLG.FileName.ToString()
wValue.Text = ReadIni(OpenFile, Isolation, Value, "")
ElseIf DialogResult = Windows.Forms.DialogResult.Cancel Then
End If
End Sub
I would like the OpenFile variable in the Save Button, the code I want to use is:
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles saveINI.Click
System.IO.File.WriteAllText(OpenFile, "")
writeIni(OpenFile, BuildOptions, Isolation, w.Value.Text)
End Sub
But the OpenFile variable is not available.
Is there any possibility to set the OpenFile variable Global?
I cannot move it outside the SUB because the Open File button doesn't work anymore.
Thanks!

The solution is very simple. Just declare OpenFile outside of sub
Private OpenFile as String
Private Sub OpenINIButton_Click( ...
Remove Dim statement Dim OpenFile = replace with just OpenFile =
Optionally test whether the variable was set at the beginning of Button2_Click
If OpenFile is Nothing then Exit Sub

Related

VB.NET filecopy program Error : System.NullReferenceException in FolderBrowserDialog1

I am trying to make a program which copies files from one folder to another and I am also using a progress bar to see what files are copying. When I am running this program I am getting an error on folderbrowserdialog1. The error is System.NullReferenceException. When I am running the program I am able to open the application but when i select the button it gives me an error.
Public Class Form1
Dim my As System.Diagnostics.Process = System.Diagnostics.Process.GetCurrentProcess
Dim directoryTargetLocation As String 'Selected file path
Dim Destinydirectory As String 'Selected dest directory path
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim FolderBrowserDialog1 As Object = Nothing
FolderBrowserDialog1.Description = "Select directory" **// Gettig error in this Line**
With FolderBrowserDialog1
If .ShowDialog() = DialogResult.OK Then
directoryTargetLocation = .SelectedPath
TextBox1.Text = directoryTargetLocation.ToString
Button2.Enabled = True
End If
End With
End Sub
Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click
FolderBrowserDialog2.Description = "Select destiny directory"
With FolderBrowserDialog2
If .ShowDialog() = DialogResult.OK Then
Destinydirectory = .SelectedPath
TextBox2.Text = Destinydirectory.ToString
TextBox2.Text = TextBox2.Text.Remove(TextBox2.Text.Length - 1) &
TextBox1.Text.Substring(TextBox1.Text.LastIndexOf("\"))
Button3.Enabled = True
End If
End With
End Sub
You declared FolderBrowserDialog1 as an object.
What you want to do is to declare it as a FolderBrowserDialog.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FolderBrowserDialog1 As New FolderBrowserDialog
FolderBrowserDialog1.Description = "Select directory"
With FolderBrowserDialog1
If .ShowDialog() = DialogResult.OK Then
directoryTargetLocation = .SelectedPath
TextBox1.Text = directoryTargetLocation.ToString
Button2.Enabled = True
End If
End With
End Sub
You have not created a FolderBrowserDialog1 object.
Edit
You were close!
What you need is:
Dim FolderBrowserDialog1 As New FolderBrowserDialog
This creates a new FolderBrowserDialog object.
What you have is:
Dim FolderBrowserDialog1 As Object = Nothing
Which creates a new generic object name FolderBrowserDialog1, and explicitly sets it to be "nothing"
This means it does not have any of the properties or methods you were referencing, so you get the error.

File is not shown in OpenFileDialog

I'm trying to do something like a text editor in VB 2012, so I have a MenuStrip with an "OpenFile" option. When it's clicked it fires an OpenFileDialog control and shows me just the files with the extension I want. The problem is that if I close the file with another option in the menu strip, when I want to open the same file I opened the first time using the same OpenFile option the OpenFileDialog is not showing me the file.
Do you know why is that?
Here is how I open the file:
Private Sub OpenFileToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenFileToolStripMenuItem.Click
'Open File
If OpenFile.ShowDialog() = Windows.Forms.DialogResult.OK Then
If Not (OpenFile.FileName = "") And OpenFile.CheckFileExists Then
NewFile = New StreamReader(OpenFile.FileName)
If NewFile IsNot Nothing Then
Me.TextBox_Main.Text = NewFile.ReadToEnd
Me.TabPage1.Text = OpenFile.FileName.Substring(OpenFile.FileName.LastIndexOf("\") + 1)
End If
End If
End If
End Sub
And here is how I close the file:
Private Sub CloseFileToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CloseFileToolStripMenuItem.Click
'Close Files
If NewFile IsNot Nothing Then
NewFile.Close()
NewFile = Nothing
End If
Me.TextBox_Main.Text = ""
Me.TabPage1.Text = "New Tab"
End Sub

vb.net get contextmenustrip applicable to multiple pictureboxes

In my form I have several pictureboxes and one contextmenustrip, the contextmenustrip is supposed to use at all these pictureboxes.
A tool in the contextmenustrip is to open and view the a pdf file.
The current code is:
Private Sub ViewToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ViewToolStripMenuItem.Click
Process.Start("C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe", "C:\vb_test\" + picDrawing(1))
End Sub
I have no idea how the tool can determine which picturebox is focused and open different files.
I am using vb.net.
It seems that ContextMenu.SourceControl returns always Nothing in particular situations. I verified this problem on VS2010 when I put my ToolStripMenuItem inside a ToolStripDropDownMenu. So the answer posted by #Justin Ryan couldn't working.
A workaround could be manually set a variable when opening ContextMenu with its SourceControl.
Public Class Form1
Dim ctrlSourceControl As Control
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
AddHandler Me.ContextMenuStrip1.Opening, AddressOf setSourceControl
End Sub
Private Sub setSourceControl(sender As Object, e As System.ComponentModel.CancelEventArgs)
Me.ctrlSourceControl = CType(sender, ContextMenuStrip).SourceControl
End Sub
Private Sub Item1ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles Item1ToolStripMenuItem.Click
MsgBox(Me.ctrlSourceControl.Name)
End Sub
End Class
From this question, Tim Lentine shows how to use the SourceControl property Of a ContextMenuStrip to determine the control which opened the context menu:
Private Sub mnuWebCopy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuWebCopy.Click
Dim myItem As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
Dim cms As ContextMenuStrip = CType(myItem.Owner, ContextMenuStrip)
MessageBox.Show(cms.SourceControl.Name)
End Sub
This answer is likely the same as tezzo's. Just used to this
scenario a lot, and wanted to share some security checks among many
others that may help.
Assuming
ONLY PictureBoxes can show your ContextMenu named MyContextMenu :
and you have a ToolStripMenuItem named ViewToolStripMenuItem
Declarations :
Option Strict On
Option Explicit On
Option Infer Off
Imports System.IO
' File.Exist()
Imports System.Diagnostics
' Process.Start()
Public Class Form1
Private p_SelectedPictureB As PictureBox
Private p_AcroRedPath As String = "C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe"
Private p_ImageFolderPath As String = "C:\vb_test\"
Private p_TargetFileName As String = ""
' ...
End Class
Handle the Opening Event of your MyContextMenu [ContextMenu]
either by a Handles MyContextMenu.Opening hook
or AddHandler MyContextMenu.Opening, AddressOf MyContextMenu_Opening
Private Sub MyContextMenu_Opening( _
sender As Object, e As System.ComponentModel.CancelEventArgs) _
Handles MyContextMenu.Opening ' Requires Private WithEvents MyContextMenu
'Try
p_SelectedPictureB = DirectCast(MyContextMenu.SourceControl, PictureBox)
If p_SelectedPictureB.Image IsNot Nothing Then
ViewToolStripMenuItem.Enabled = True
Select Case True
Case p_SelectedPictureB Is PictureBox1:
p_TargetFileName = picDrawing(1)
ViewToolStripMenuItem.Text = "Open [" + p_TargetFileName + "]"
Case p_SelectedPictureB Is PictureBox2:
p_TargetFileName = picDrawing(2)
ViewToolStripMenuItem.Text = "Open [" + p_TargetFileName + "]"
' ...
Case Else
ViewToolStripMenuItem.Enabled = False
ViewToolStripMenuItem.Text = "Open [<Wrong PBox>]"
p_TargetFileName = ""
'e.Cancel = True
End Select
Else
ViewToolStripMenuItem.Enabled = False
ViewToolStripMenuItem.Text = "Open [<No Image>]"
p_TargetFileName = ""
'e.Cancel = True
End If
'Catch CurrentException As Exception
' MessageBox.Show(CurrentException.Message)
' ViewToolStripMenuItem.Enabled = False
' p_TargetFileName = ""
' e.Cancel = True
'End Try
' ^^ remove commenting if you're unsure.
End Sub
Prefer the use of top declared variables.
If you write plain file/folder paths inside a method or function, you could loose track of it quickly, and some time later, you don't understand why your application suddenly started to crash (because the file went deleted/application uninstalled, or the folder renamed)
=> Put path to File/Folder in a global variable
However, the best move is to retrieve that path at Runtime, and ensure the existence of the File/Folder before going further...
Private Sub ViewToolStripMenuItem_Click( _
sender As Object, e As EventArgs) _
Handles ViewToolStripMenuItem.Click
Dim TargetFile As String = p_ImageFolderPath + p_TargetFileName
If File.Exists(TargetFile) Then
' (p_AcroRedPath existence checked when application starts)
Process.Start(p_AcroRedPath, TargetFile)
Else
MessageBox.Show("The File [" + TargetFile + "] doesn't exist.")
End If
End Sub

How do I change the value of a specific DataGridView Cell?

I've been trying to add a feature to my program that allows you to choose a file using OpenFileDialog (when you double click on a DataGridView cell) and change the value of that cell to the path of the file you chose. I have no idea what the command is to do that. I've tried to guess and I looked up on the internet and couldn't find anything.
Private Sub dgSound_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgSound.CellDoubleClick
If e.ColumnIndex = 3 Then 'Index of "file" column
Dim file As String = ""
OpenFileDialog1.ShowDialog()
file = OpenFileDialog1.FileName
'Contents of cell that was clicked = file
End If
End Sub
I'd use CellClick rather than CellContentClick as follows...
Private Sub dgSound_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgSound.CellClick
If e.ColumnIndex = 3 Then 'Index of "file" column
Dim file As String = ""
OpenFileDialog1.ShowDialog()
file = OpenFileDialog1.FileName
'Contents of cell that was clicked = file
dgSound.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = file
End If
End Sub

How to op-en file and view in a rich text box using vb.net?

Hi I am trying to open and view a files text in a rich text box. Here is what I have please let me know what I am doing wrong?
Private Sub loadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles loadButton.Click
' Displays an OpenFileDialog so the user can select a Cursor.
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.Filter = "Cursor Files|*.txt"
openFileDialog1.Title = "Select a Cursor File"
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
' Assign the cursor in the Stream to the Form's Cursor property.
Me.mainRTBox = New Text(openFileDialog1.OpenFile())
End If
End Sub
The problem you were having was that you weren't reading the file at all, and you weren't assigning the content of the file to the RichTextBox correctly.
Specifically, this code you have:
Me.mainRTBox = New Text(openFileDialog1.OpenFile())
.. should be:
Me.mainRTBox.Text = FileIO.FileSystem.ReadAllText(openFileDialog1.FileName)
This code will work:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Displays an OpenFileDialog so the user can select a Cursor.
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.Filter = "Cursor Files|*.cur"
openFileDialog1.Title = "Select a Cursor File"
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
' Assign the cursor in the Stream to the Form's Cursor property.
Dim extension = openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf("."))
If extension Is "cur" Then
Me.mainRTBox.Text = FileIO.FileSystem.ReadAllText(openFileDialog1.FileName)
End If
End If
End Sub
End Class
Edit: I updated the code so that it checks if the user did actually open a Cur (cursor) file.
RichTextBoxes have a built in function for viewing RTF files and TXT files.
Code for a RTF file:
RichTextBox1.LoadFile("YOUR DIRECTORY", RichTextBoxStreamType.RichText)
Code for a TXT file:
RichTextBox1.LoadFile("YOUR DIRECTORY", RichTextBoxStreamType.PlainText)
Hope it helps
-nfell2009