VB.NET ~ How can I encapsulate my code to be used over and over? - vb.net

I know I seem to ask the same types of questions but with much trial and error I finally got my app to do what I needed it to do. I have a form with a button on it. When clicked it creates a form, a web browser, a picture box, a text box, and a button.
The web browser, picture box, textbox, and the button are all placed onto this form at run time.
My question is now how can I encapsulate this to be used over and over again. I've tried just putting this into a class and creating an instance of the class but I keept getting an error on my document completing stating my code isn't referring to an object.
But here is my code.
Thanks
Public Class CaptchaWindow
Dim myform As New Form
Dim webbrowser As New WebBrowser
Dim picturebox As New PictureBox
Dim textbox As New TextBox
Dim submitbtn As New Button
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ProfileMaker.Show()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Call myspecs()
AddHandler submitbtn.Click, AddressOf captchasubmit
AddHandler webbrowser.DocumentCompleted, AddressOf webcompleteddesignfloat
webbrowser.Navigate("http://www.designfloat.com/register/")
End Sub
Sub myspecs()
'FORM SIZE AND LOCATION
myform.Size = New Drawing.Size(1542, 771)
myform.Location = New Drawing.Point(15, 15)
'WEBBROWSER SIZE AND LOCATION
webbrowser.Size = New Drawing.Size(1000, 577)
webbrowser.Location = New Drawing.Point(12, 181)
webbrowser.ScriptErrorsSuppressed = True
'PICTUREBOX SIZE AND LOCATION
picturebox.Size = New Drawing.Size(299, 83)
picturebox.Location = New Drawing.Point(12, 12)
picturebox.BorderStyle = BorderStyle.Fixed3D
'TEXBOX SIZE AND LOCATION
textbox.Size = New Drawing.Size(299, 20)
textbox.Location = New Drawing.Point(12, 101)
'BUTTON SIZE AND LOCATION
submitbtn.Size = New Drawing.Size(75, 23)
submitbtn.Location = New Drawing.Point(118, 127)
submitbtn.Text = "Submit"
myform.Controls.Add(webbrowser)
myform.Controls.Add(picturebox)
myform.Controls.Add(textbox)
myform.Controls.Add(submitbtn)
myform.Show()
End Sub
Sub webcompleteddesignfloat()
For Each element As HtmlElement In webbrowser.Document.GetElementsByTagName("input")
If element.GetAttribute("name") = "reg_username" Then
element.SetAttribute("value", ProfileMaker.Username.Text)
End If
Next
For Each element As HtmlElement In webbrowser.Document.GetElementsByTagName("input")
If element.GetAttribute("name") = "reg_email" Then
element.SetAttribute("value", ProfileMaker.Email.Text)
End If
Next
For Each element As HtmlElement In webbrowser.Document.GetElementsByTagName("input")
If element.GetAttribute("name") = "reg_password" Then
element.SetAttribute("value", ProfileMaker.Password.Text)
End If
Next
For Each element As HtmlElement In webbrowser.Document.GetElementsByTagName("input")
If element.GetAttribute("name") = "reg_password2" Then
element.SetAttribute("value", ProfileMaker.Password.Text)
End If
Next
If webbrowser.ReadyState = WebBrowserReadyState.Complete Then
For Each Captcha As HtmlElement In webbrowser.Document.Images
If Captcha.GetAttribute("src").Contains("http://www.google.com/recaptcha/api/image? c=") Then
picturebox.Load(Captcha.GetAttribute("src"))
End If
Next
End If
End Sub
Sub captchasubmit()
If webbrowser.ReadyState = WebBrowserReadyState.Complete Then
For Each Captcha As HtmlElement In webbrowser.Document.Images
If Captcha.GetAttribute("src").Contains("http://www.google.com/recaptcha/api/image?c=") Then
picturebox.Load(Captcha.GetAttribute("src"))
End If
Next
End If
For Each element As HtmlElement In webbrowser.Document.GetElementsByTagName("input")
If element.GetAttribute("id") = "recaptcha_response_field" Then
element.SetAttribute("value", textbox.Text)
End If
Next
For Each element As HtmlElement In webbrowser.Document.GetElementsByTagName("button")
If element.GetAttribute("name") = "submit" Then
element.InvokeMember("click")
End If
Next
myform.Dispose()
End Sub
The below part is when I tried to create an instance of this from a class.
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim mystuff As New CaptchaClass
mystuff.Handler()
mystuff.captchasubmit()
mystuff.webcompleteddesignfloat()
End Sub
End Class

You should Imports your class namespace to the current scope (page) at the beggining of the code
Imports Namespace.CaptchaWindow
Class Page1
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim mystuff As New CaptchaClass
End Sub
End Class
Also look at Namespaces if you doesn't know what it is.

Related

How to customize the click event of dynamically created buttons from string array?

Here is the code I have:
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddNewButton()
End Sub
Public Sub AddNewButton()
Dim buttonTop As Integer = 100
For Each item As String In Globals.candidates
Dim btn As New System.Windows.Forms.Button()
Dim Location As New Point(100, (buttonTop + 20))
btn.Location = Location
btn.Text = item
btn.Width = 150
AddHandler btn.Click, AddressOf Me.buttonClick
Me.Controls.Add(btn)
buttonTop += 20
Next
End Sub
Private Sub buttonClick()
Dim result As Integer = MessageBox.Show(String.Format("Did you select {0} ?", ???????????), "Confirmation", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
MessageBox.Show("Yes pressed")
Else
MessageBox.Show("No pressed")
End If
End Sub
End Class
Globals.candidates is a global string array variable that holds a name "LastName, FirstName" and when the form is loaded I call the AddNewButton() Sub and it creates buttons for each item in the string array. No problem.
If you see in my code the "??????????" section, I don't know how to reference the dynamically created buttons's text so that I can display the proper "Did you select thisButton.text" properly.
Any help is appreciated.
Thanks!
EDIT:
Code changed as per suggestions: (Working)
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddNewButton()
End Sub
Public Sub AddNewButton()
Dim buttonTop As Integer = 100
For Each item As String In Globals.candidates
Dim btn As New System.Windows.Forms.Button()
Dim Location As New Point(100, (buttonTop + 20))
btn.Location = Location
btn.Text = item
btn.Width = 150
AddHandler btn.Click, AddressOf Me.buttonClick
Me.Controls.Add(btn)
buttonTop += 20
Next
End Sub
Private Sub buttonClick(sender As Object, e As EventArgs)
Dim btn As Button = DirectCast(sender, System.Windows.Forms.Button)
Dim result As Integer = MessageBox.Show(String.Format("Did you select {0} ?", btn.Text), "Confirmation", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
MessageBox.Show("Yes pressed")
Else
MessageBox.Show("No pressed")
End If
End Sub
End Class
You need to put the proper signature on your event handler:
Private Sub buttonClick(sender As Object, e As EventArgs)
Then, you can use the sender object (which will be whichever button was clicked)
Dim button As Button = DirectCast(sender, System.Windows.Forms.Button)
Dim result As Integer = MessageBox.Show(String.Format("Did you select {0} ?", button.Text), "Confirmation", MessageBoxButtons.YesNo)
To get a reference to the button clicked you need to declare the event handler of the button click with the two parameters that are passed to it by the form engine.
Private Sub buttonClick(sender as Object, e as EventArgs)
Now, this correct event handler receives a parameter named sender that is the control reference to the button clicked. You could cast it to a button and then extract the Text property
Private Sub buttonClick(sender as Object, e as EventArgs)
Dim btn = DirectCast(sender, System.Windows.Forms.Button)
if btn IsNot Nothing then
Dim result As Integer = MessageBox.Show(String.Format("Did you select {0} ?", btn.Text), "Confirmation", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
MessageBox.Show("Yes pressed")
Else
MessageBox.Show("No pressed")
End If
End If
End Sub
This should be enough in this simple case where you have just a string data, but, if you need to associate a more complex object (like an instance of a Person class for example) you could use the Tag property of every dynamically added button to store there a reference to the instance of the class
As a side note, your code works also without the declaration of the two parameters because you have the Option Strict configuration set to OFF. This is a bad practice because it introduces subtle errors in you parameters usage and in automatic conversions of type. If you are just starting with a new project remember to set its property Option Strict to ON

Create list box in runtime and change its color via menu in runtime

I need to write this small program in visual basic, but i face a problem which is i can't change the color or add list form text file during runtime.
this is picture of what i wont to do
http://i62.tinypic.com/30tghh0.png
And this is the code i wrote so far,,
Public Class Form1
Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click
Dim listBox1 As New System.Windows.Forms.ListBox
listBox1.Text = "New List"
listBox1.Location = New Point(25, 25)
listBox1.Size = New Size(380, 280)
Me.Controls.Add(listBox1)
OpenToolStripMenuItem.Enabled = True
SaveToolStripMenuItem.Enabled = True
SaveAsToolStripMenuItem.Enabled = True
CloseToolStripMenuItem.Enabled = True
EditToolStripMenuItem.Enabled = True
End Sub
Private Sub ExirToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExirToolStripMenuItem.Click
End
End Sub
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
If (OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
Dim myfile As String = OpenFileDialog1.FileName
Dim allLines As String() = File.ReadAllLines(myfile)
For Each line As String In allLines
ListBox1.Items.Add(line)
Next
End If
End Sub
End Class
The problem as you see is in OpenToolStripMenuItem sub with line ListBox1.Items.Add(line)
is there is no listbox1 because is not created yet.the same with color, save and the rest.
so, please help me to solve it.
Move the declaration of ListBox1 out to the Class level:
Public Class Form1
Private ListBox1 As System.Windows.Forms.ListBox
Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripMenuItem.Click
ListBox1 = New System.Windows.Forms.ListBox
...
End Sub
...
End Class
*But why create it at run-time like this? You could add it at design-time and set the Visible() property to False. When the New button is clicked, you change Visible() to True. Unless you need a new ListBox to be created each time so you have more than one? If so, how will they be laid out?...

VB Clicked Links Open In New Tab

I've been searching around for a while for some code to do this, and I found a couple. most of them didn't work but I'm trying to get this one to work.
Private Sub WebBrowser1_NewWindow(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles WebBrowser1.NewWindow
'This creates a new tab
Dim tp As New TabPage
TabControl1.Controls.Add(tp)
'This creates a new webbrowser with the NewWindow Event
'And navigates it to the link wanting to be opened
Dim wb As New WebBrowser
Dim myElement As HtmlElement = WebBrowser1.Document.ActiveElement
Dim target As String = myElement.GetAttribute("href")
With wb
.Navigate(target)
.Dock = DockStyle.Fill
End With
AddHandler wb.NewWindow, AddressOf WebBrowser_NewWindow
tp.Controls.Add(wb)
'This prevents ie from popping up
e.Cancel = True
End Sub
But then I get a error on here WebBrowser_NewWindow, and when I check and see what it says and I am told WebBrowser_NewWindow Is Not Declared. It may be inaccessible due to protection level How am I supposed to fix this?
Full Code
Public Class Form2
Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.BringToFront()
WebBrowser1.Navigate("www.google.com")
End Sub
Private Sub IClarityButton2_Click_1(sender As Object, e As EventArgs) Handles IClarityButton2.Click
If TextBox2.Text = "Close" Then
End
Else
TextBox2.Text = "Invalid"
End If
End Sub
Private Sub WebBrowser1_NewWindow(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles WebBrowser1.NewWindow
'This creates a new tab
Dim tp As New TabPage
TabControl1.Controls.Add(tp)
'This creates a new webbrowser with the NewWindow Event
'And navigates it to the link wanting to be opened
Dim wb As New WebBrowser
Dim myElement As HtmlElement = WebBrowser1.Document.ActiveElement
Dim target As String = myElement.GetAttribute("href")
With wb
.Navigate(target)
.Dock = DockStyle.Fill
End With
'AddHandler wb.NewWindow, AddressOf WebBrowser_NewWindow
tp.Controls.Add(wb)
'This prevents ie from popping up
e.Cancel = True
End Sub
End Class
Try removing AddHandler wb.NewWindow, AddressOf WebBrowser_NewWindow

vb.net passing variables between controls

here is my code
Public Sub Personalize_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each fi As FileInfo In New DirectoryInfo(Application.StartupPath + "\web").GetFiles
Dim pictooltip As New ToolTip
Dim pbx As New Button
AddHandler pbx.Click, AddressOf pbx_click
pbx.Width = 150
pbx.Height = 150
pbx.BackgroundImage = Image.FromFile(fi.FullName)
wallpapers.Controls.Add(pbx)
pbx.Cursor = Cursors.Hand
pictooltip.SetToolTip(pbx, fi.Name)
pbx.BackgroundImageLayout = ImageLayout.Stretch
Next
End Sub
Private Sub pbx_click()
main.BackgroundImage = Image.FromFile(fi.FullName)
End Sub
i can't figure how to use "fi" in pbx_click()
any hint for that ??
Just put the FullName() into the Tag() property of the Button and pull it back out when it gets clicked:
Dim pbx As New Button
pbx.Tag = fi.FullName
Pulling it back out:
Private Sub pbx_click()
main.BackgroundImage = Image.FromFile(DirectCast(sender, control).Tag.ToString())
End Sub
Try this,
Public Class Form1
Dim fi as FileInfo
Public Sub Personalize_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each Me.fi In New DirectoryInfo(Application.StartupPath + "\web").GetFiles
Dim pictooltip As New ToolTip
Dim pbx As New Button
AddHandler pbx.Click, AddressOf pbx_click
pbx.Width = 150
pbx.Height = 150
pbx.BackgroundImage = Image.FromFile(fi.FullName)
wallpapers.Controls.Add(pbx)
pbx.Cursor = Cursors.Hand
pictooltip.SetToolTip(pbx, fi.Name)
pbx.BackgroundImageLayout = ImageLayout.Stretch
Next
End Sub
Private Sub pbx_click()
main.BackgroundImage = Image.FromFile(fi.FullName)
End Sub
End Class
Your Fi is declared locally in the first subroutine (or sub).
Declare Fi outside of the Personalize_Load sub, then pass data to it.
Dim fi as String = ""
Public Sub Personalize_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each fii As FileInfo In New DirectoryInfo(Application.StartupPath + "\web").GetFiles
Dim pictooltip As New ToolTip
Dim pbx As New Button
AddHandler pbx.Click, AddressOf pbx_click
pbx.Width = 150
pbx.Height = 150
pbx.BackgroundImage = Image.FromFile(fii.FullName)
fi = fii.FullName
wallpapers.Controls.Add(pbx)
pbx.Cursor = Cursors.Hand
pictooltip.SetToolTip(pbx, fi.Name)
pbx.BackgroundImageLayout = ImageLayout.Stretch
Next
End Sub
Private Sub pbx_click()
main.BackgroundImage = Image.FromFile(fi)
End Sub
You can then use pbx_click() by simply calling it on any sub, or trying it to a handler.
Change your event to this:
Private Sub pbx_click(sender As Object, e As System.EventArgs)
main.BackgroundImage = Image.FromFile(DirectCast(sender, Button).BackgroundImage)
End Sub
Or, you can use the Tag property and store some serialized data. See here: Add parameter to Button click event

danamically creating controlltabs that can be used

I'm trying to dynamically create tabcontrols which works fine; the tabs are being created however. Once created I would also like them to become clickable and execute other code, this now posing a problem.
The code I’m using to create a tab is as follows
' do whatever wtih filename
Dim myTabPage As New TabPage()
myTabPage.Text = TextBox4.Text
TabControl1.TabPages.Add(myTabPage)
TabPage1.Hide()
Not so nice cause I can now fill my form with as many tabs as I like however none of them can be clicked to execute futher code???
EDIT:
Private Sub TabControl_SelectedIndexchaged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
Dim TabName As String
TabName = TabControl1.SelectedTab.Name
If TabName.Contains("TabPage") Then
' Do something
MsgBox("new tab created")
End If
End Sub
You have to add an event handler for the TabPage click event:
Dim myTabPage As New TabPage
myTabPage.Text = TextBox4.Text
AddHandler myTabPage.Click, AddressOf TabPage1_Click
TabControl1.TabPages.Add(myTabPage)
Which will call this code:
Private Sub TabPage1_Click(sender As Object, e As EventArgs)
MessageBox.Show(DirectCast(sender, TabPage).Text)
End Sub
Per your edit, you would have to add the name property:
myTabPage.Name = TextBox4.Text
And your SelectedIndexChanged event:
Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) _
Handles TabControl1.SelectedIndexChanged
If TabControl1.SelectedTab IsNot Nothing Then
MessageBox.Show(TabControl1.SelectedTab.Name)
End If
End Sub