-
Jun 26th, 2019, 01:08 PM
#1
Thread Starter
Hyperactive Member
[RESOLVED] Extract filename from textbox
I want to extract filename from textbox´s filepath, but it does not work.
InputFile is read-only textbox.
I´ve tried:
Code:
Dim nazovsuboru As String = IO.Path.GetFileNameWithoutExtension(InputFile.Text)
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
MsgBox(nazovsuboru)
End Sub
Error: An error occurred creating the form. See Exception.InnerException for details. The error is: Object reference not set to an instance of an object.
I´ve looked at many different solutions, but none of that works for me. Thanks a lot.
-
Jun 26th, 2019, 01:16 PM
#2
Re: Extract filename from textbox
Move the variable declaration inside the Sub.
Variables declared outside of routines are created when the form is first created, and any value assigned will happen at that time (not when the button is pressed). That means the value will only be correct if it would have been correct before the user could see the form.
On top of that, due to the way forms are created, the textbox doesn't exist at the time you are setting the variable (and that is what is giving the error).
Moving the variable declaration (or just the part that sets the value) inside the sub fixes both of those issues.
-
Jun 26th, 2019, 09:14 PM
#3
Re: Extract filename from textbox
As si suggests, you definitely need to at least move the assignment, if not the declaration, inside the event handler:
vb.net Code:
Dim nazovsuboru As String Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click nazovsuboru = IO.Path.GetFileNameWithoutExtension(InputFile.Text) MessageBox.Show(nazovsuboru) End Sub
If you need to use that same variable in some other method as well, or it needs to retain its value between invocations of that one method, then that's what you should do. If the variable is only used in that one method and it doesn't have to retain its value between calls, declare the variable inside the method too. In that case, the variable ceases to exist when the method completes and starts existing again the next time that method is called.
-
Sep 7th, 2019, 01:54 PM
#4
Thread Starter
Hyperactive Member
Re: [RESOLVED] Extract filename from textbox
Thanks jmcillhinney! It works now!
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|