Form_Load doesn't execute in application - vb.net

I am new to Visual Basic. I have installed Microsoft Visual Studio 2010. Created a new Windows Form Application. As an example, I made a simple program which will ask the end user to input 2 numbers and allow them to either add them or subtract the second number from the first one and display the output in a Textbox.
Now, I added another Subroutine which would be executed automatically when the Windows Form loads. This would calculate the width of the output Textbox and the Form Width and display at the bottom.
This is how the code looks like right now:
Public Class Form1
' Run this Subroutine initially to display the Form and Text box width
Private Sub Form_Load()
Label5.Text = TextBox3.Width
Label7.Text = Me.Width
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim a As Integer
Dim b As Integer
a = TextBox1.Text
b = TextBox2.Text
TextBox3.Text = a + b
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim a As Integer
Dim b As Integer
a = TextBox1.Text
b = TextBox2.Text
TextBox3.Text = a - b
End Sub
End Class
While everything works correctly for the addition and subtraction, it does not display the Form and output Textbox width in the Windows Form.
I think, Form_Load() is not executing properly.
I also tried, Form_Activate() but that did not work either.
Once I am able to do this, I would like to extend this concept to resize the output Textbox along with the Form resize. However, for the purpose of understanding I wanted to see if I can execute Form_Load() successfully.
Thanks.

Form_Load doesn’t execute. For now, it’s just any other method. In order to tell VB to make this method handle the Load event, you need to tell it so:
Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Loasd
Label5.Text = TextBox3.Width
Label7.Text = Me.Width
End Sub
(And add the required parameters for the event.)
A few other remarks:
Ensure that Option Strict On is enabled in your project options at all times. This will make the compiler much stricter with your code and flag more errors. This is a good thing since these errors are potential bugs. In particular, your code is very lax with conversions between different data types, these should be made explicit.
Initialise variables when you declare them, don’t assign a value in a separate statement. That is, write this:
Dim a As Integer = Integer.Parse(TextBox1.Text)
(Explicit conversion added as well.)
If you want to make a control fill the form, you can just set its Dock property appropriately in the forms editor, instead of having to program this manually.

You need to add the Handle so the app executes it automatically:
Private Sub Form_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
'...
End Sub

Related

How do I allow null textbox when using bindingsource Find method?

I am new to VB please assist. I have an application where I search using combo box and two textboxes. Now it is not always when all textboxes have text. Sometimes the user can search using one textbox. My problem is when I leave out a textbox that searches an integer column is using binding source find method I get : 'Input string was not in a correct format.' because the textbox is empty. My database is access database and I am searching from a gridview binding source. How can I allow txtboxIdSize to be ignored if not used? My code below:
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
TblDiesBindingSource.Filter = $"Descript LIKE '%{txtDescription.Text.Trim()}%'"
TblDiesBindingSource.Position = TblDiesBindingSource.Find("IDSIZE", txtIdSize.Text)
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
If txtboxIdSize.TextLength > 0 then
TblDiesBindingSource.Filter = $"Descript LIKE '%{txtDescription.Text.Trim()}%'"
TblDiesBindingSource.Position = TblDiesBindingSource.Find("IDSIZE", txtIdSize.Text)
End if
End Sub

Basic math functions in VB.net

So i am currently in process of adding a basic calculator that allows the user to define 2 variables and then press a button that puts the variables into a basic math equation and presents the result but i think i have gone about it completely wrong.
this is my first time using math functions in VB and would appreciate it if someone can show me where im going wrong.
this is my code so far:
Imports System.Math
Public Class SOGACALC
Dim soga As String = Math.Abs(72 - months.Text) * opp.Text
Private Sub SOGACALC_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SOGAValue.Text = soga
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
HOME.Show()
Me.Close()
End Sub
End Class
Where you have written
Dim soga As String = Math.Abs(72 - months.Text) * opp.Text
I suspect that you are anticipating that soga will be a function of the properties referred to in that and will change when those properties change. It does not work that way.
The way to get a value which varies depending on its parameters is to define a function, so you might have:
Friend Function Soga(monthValue As Control, oppThing As Control) As String
Dim month As Integer = CInt(monthValue.Text)
Dim opp As Decimal = CDec(oppThing.Text)
Return (Math.Abs(72 - month) * opp).ToString()
End Function
and call it like:
'TODO: Give Button1 a meaningful name.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SOGAValue.Text = Soga(months, opp)
End Sub
where there are controls names "months" and "opp" on the form.
I strongly recommnend that you use Option Strict On - it points out problems in code and suggests corrections for you.
Notice that I used the Decimal type for opp - I had to guess at a suitable type because nowhere in the code you showed us was there any indication of what type it needs to be.
An improvement would be to use TryParse methods instead of CInt/CDec, so that you can inform the user if they have made a simple typing error.

Drag and drop an image into a RichTextBox

I am updating code done in VB 4, where I have a RichTextBox. I need to be able to drag-and-drop an image from Windows Explorer into the RTB. Unfortunately, I am unable to get the drag-and-drop to work.
I've created a much more simple Windows Form program to try to resolve this, but have made no progress. I begin by setting AllowDrop to True.
Public Sub New()
InitializeComponent()
Me.DragAndDropTextBox.AllowDrop = True
End Sub
I then create handlers for the RTB. These are taken directly from MSDN.
Private Sub DragAndDropTextBox_DragEnter(ByVal sender As Object, ByVal e As _
System.Windows.Forms.DragEventArgs) Handles DragAndDropTextBox.DragEnter
' Check the format of the data being dropped.
If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then
' Display the copy cursor.
e.Effect = DragDropEffects.Copy
Else
' Display the no-drop cursor.
e.Effect = DragDropEffects.None
End If
End Sub
Private Sub DragAndDropTextBox_DragDrop(ByVal sender As Object, ByVal e As _
System.Windows.Forms.DragEventArgs) Handles DragAndDropTextBox.DragDrop
System.Windows.Forms.DragEventArgs) Handles DragAndDropTextBox.DragDrop
Dim img As Image
img = Image.FromFile(e.Data.GetData(DataFormats.FileDrop, False))
Clipboard.SetImage(img)
Me.DragAndDropTextBox.SelectionStart = 0
Me.DragAndDropTextBox.Paste()
End Sub
When I grab an image in Explorer and drag it over my window, I get the circle with a slash. I have put breakpoints on the first line of each of the handlers, and they are never reached. I have looked at several pages, and they all seem to give the same process, so I must be missing something simple.
I am not worried right now about pasting the image into the text box; I know I need to work on that. I am only trying to capture the image, but the handler methods do not seem to be getting called.
UPDATE
After quite a bit of experimentation, I found that the actual issue is with my Visual Studio 2010, which I always run as administrator. When I run the program from an exe, the drag-and-drop works. When I try running from VS in debug, it does not. Has anyone experienced this before?
If anyone could shed some light on this, I would be very grateful.
Try getting rid of the InitializeComponent() call in your Sub New function. When I did that, I was able to detect the DragEnter event. Here is the code I tested (I created a simple WinForm and put a RichTextBox on it called DragAndDropTextBox):
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DragAndDropTextBox.AllowDrop = True
End Sub
Private Sub DragAndDropTextBox_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DragAndDropTextBox.DragEnter
Debug.Print("Entering text box region")
' Check the format of the data being dropped.
If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then
' Display the copy cursor.
e.Effect = DragDropEffects.Copy
Else
' Display the no-drop cursor.
e.Effect = DragDropEffects.None
End If
End Sub
Private Sub DragAndDropTextBox_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DragAndDropTextBox.DragDrop
Dim img As Image
img = Image.FromFile(e.Data.GetData(DataFormats.FileDrop, False))
Clipboard.SetImage(img)
Me.DragAndDropTextBox.SelectionStart = 0
Me.DragAndDropTextBox.Paste()
End Sub
End Class
The InitializeComponent() call should appear in your code (I believe) when you add your own custom controls to a form. Otherwise, I don't think you need to call it.
It turned out that the Drag-And-Drop was working when running the code from an exe, but not from within Visual Studio. More searching turned up this answer, which states that Drag-And-Drop does not work in Visual Studio when it is run as an Administrator. I ran it with normal permissions, and the code worked.

VB.Net trial application

how can i make my application goes to function after certain usage
like if i click an button 10 times, then button is disabled
just like trial program,
so far, i can do that on run-time only,
how can i make it count clicks without using Registry?
my program is very simple: convert strings to Base64
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = Convert.ToBase64String(New System.Text.ASCIIEncoding().GetBytes(TextBox1.Text))
End Sub
You probably need Settings. Easily Save and Retrieve Application and User Settings in VB.NET or C# Apps. First create ClickCouter of type integer with value 0 in settings (see the article).
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
My.Settings.ClickCouter +=1
My.Settings.Save()
If My.Settings.ClickCouter>=10 then Button1.Enabled = False
End Sub
It is necessary to check ClickCouter also in Form_Load. The value is stored in a file in a user profile so the solution is not too "hacker proof" (but is fool proof :-D ).

Text is selected in the text box

When I load the form where some text has been given to text box. All the text in that textbox is highlighted. I want vb not to load it this way.
How to fix it.
Thanks
Furqna
You could set the tab index on your textbox to something else so that it's not the lowest index.
You could set the TextBox1.SelectionLength = 0 in the form.activated event.
I don't like this as much because if the user had the text hilited and minized the application then they will lose the hilite, but is fairly easy to do. I guess you could use a flag to make sure it only did it on the first activate.
You could set a timer event in the load to clear it immediately after the load event, but that seems like overkill. I have worked at places where they had a standard function that happened on every form 100 ms after load because of problems such as this.
You could try this(it looks like a workaround):
Private Sub TextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus
TextBox1.SelectionStart = TextBox1.Text.Length
End Sub
It depends on the TabIndex of your TextBox, if it has the lowest TabIndex it gets focus and therefore it's Text is selected.
' VS.net 2013. Use the "Shown" event.
' GotFocus isn't soon enough.
Private Sub Form_Shown(sender As Object, e As EventArgs) Handles Me.Shown
TB.SelectionLength = 0
End Sub
Type 1 Method
Dim speech = CreateObject("sapi.spvoice")
speech.speak(TextBox1.Text)
Type 2 Method
Dim oVoice As New SpeechLib.SpVoice
Dim cpFileStream As New SpeechLib.SpFileStream
'Set the voice type male or female and etc
oVoice.Voice = oVoice.GetVoices.Item(0)
'Set the voice volume
oVoice.Volume = 100
'Set the text that will be read by computer
oVoice.Speak(TextBox1.Text, SpeechLib.SpeechVoiceSpeakFlags.SVSFDefault)
oVoice = Nothing
Type 3 Method
Imports System.Speech.Synthesis
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim spk As New SpeechSynthesizer
For Each voice As InstalledVoice In spk.GetInstalledVoices
ListBox1.Items.Add(voice.VoiceInfo.Name)
Next
ListBox1.SelectedIndex = 0
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim spk As New SpeechSynthesizer
spk.SelectVoice(ListBox1.SelectedItem.ToString)
spk.Speak(TextBox1.Text)
End Sub
End Class
This will also happen sometimes if The TextChanged or other similar Event is fired twice for the control.
When creating each form. Each object is indexed you can set the tab Index higher then the indexed object. Example: On the third form you put a text box in.
private void textBox1_TextChanged(object sender, EventArgs e)
This was the 12th object in the project, it would be indexed at 12. if you put the tab index higher then the indexed objects throughout the project. Tab index 1000 (problem solved.)
Have a great day.
Scooter