Moving .NET controls at runtime - vb.net

I am attempting to move all controls on a form down or up by the height of a menubar depending on whether it is visible or not. I have code which I think ought to work well for this, however it seems that Me.Controls is empty at runtime, so my for each loop is never entered. Could someone please offer a suggestion as to how I can move the controls?
Private Sub uxMenuStrip_VisibleChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles uxMenuStrip.VisibleChanged
For Each control As Control In Me.Controls
If control.Name <> "uxMenuStrip" Then
Dim temp As AnchorStyles = control.Anchor
control.Anchor = AnchorStyles.None
control.Top -= ((CInt(uxMenuStrip.Visible) * 2 - 1) * uxMenuStrip.Height)
control.Anchor = temp
End If
Next
Me.Height += ((CInt(uxMenuStrip.Visible) * 2 - 1) * uxMenuStrip.Height)
End Sub

Add a new Handler with Control and change location in address
Public Sub ChngPostion(ByVal sender As System.Object, ByVal e As System.EventArgs)
For Each cntrl As Control In Me.Controls
If cntrl.Name = sender.Name Then
cntrl.Location = New System.Drawing.Point(sender.Location.X,sender.Location.Y)
End If
Next
End Sub

As Michael Todd points out, Me.Controls can't be empty. Also, this might not work as well as you're thinking. Controls on WinForms apps are hierarchical. The only way to do this 100% cleanly is to make the move code recursive. IE, perform the same operation on every control in each control's controls collection. (Now I'm sounding like Dr. Seuss...) If your form is simple, this wouldn't be an issue, obviously.
At the end of the day, though, you'll probably be better off just putting everything on the form inside a Panel and just moving the Panel control explicitly by name. It would make what you're trying to do more clear.

Try this:
Private Sub uxMenuStrip_VisibleChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxMenuStrip.VisibleChanged
Dim menu As Control = sender
Dim dh As Integer = IIf(menu.Visible, 1, -1) * menu.Height
For Each control As Control In Controls
If control.Parent Is Me And Not control Is menu Then
control.Top += dh
End If
Next
Height += dh
End Sub
Update:
Anyway, i strongly recomment using container, in case with MenuStrip - ToolStripContainer.

Related

How do I set the tabIndex for a Button at run time in WinForms?

I have a generic message box where we have a few panels in which we add controls at runtime.
Here in my form, I've already pnlBottom on which pnlButtons is there along with some other controls.
Now at run time I'm adding an OK button to pnlButtons which is there on pnlBottom. I'm not setting a TabIndex for any controls in the Designer.vb file.
I'm trying to keep the focus on the OK button using the code below, but it's not working.
For Each control As Control In Me.Controls
If TypeOf (control) Is Panel Then
Dim pnlBottons As Panel = CType(control, Panel)
If pnlBottons.Name = "pnlBottom" Then
For Each ctrl As Control In control.Controls
Dim pnlButtons As Panel = CType(ctrl, Panel)
If pnlButtons.Name = "pnlButtons" Then
For Each ctrlbtn As Control In ctrl.Controls
If TypeOf (ctrlbtn) Is Button Then
Dim textBox As Button = CType(ctrlbtn, Button)
textBox.Parent.Parent.TabIndex = 0
textBox.Parent.TabIndex = 0
textBox.TabIndex = 0
End If
Next
End If
Next
End If
End If
Next
Here I'm setting the TabIndex for pnlBottom, pnlButtons and OK button as 0.
Please suggest how to focus the OK button.
You can set the focus on a control during Form Load event using either of the following options. (Ref: How to set the focus on a control when the form loads in Visual Basic .NET or in Visual Basic 2005. The original link is broken, so use Wayback Machine.)
1- Control.Select Method
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Mybase.Load
Me.OKButton.Select()
End Sub
Focus is a low-level method intended primarily for custom control
authors. Instead, application programmers should use the Select method
or the ActiveControl property for child controls, or the Activate
method for forms.
2- Form.ActiveControl Property
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Mybase.Load
Me.ActiveControl = Me.OKButton
End Sub
3- Control.Focus Method
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Mybase.Load
Me.Show()
Me.OKButton.Focus()
End Sub
The reason that we call Me.Show() is to set forms visible to true. according to:
You can use the Control.Focus method in the Load event of the form to
set the focus on a control only after the Visible property of the form
is set to True.
In cases you can not use Me.OKButton you can find the control you want like this:
Dim control = Me.Controls.Find("OKButton", True).FirstOrDefault()
If Not control Is Nothing Then
control.Select() 'or other stuff
End If

Form_Load doesn't execute in application

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

Need help using Checkbox

i have a couple of questions about my basic project
if i have a check box and when its checked, it is going to a text box which is displaying the price, when i uncheck it my price still says in that text box, how can i make it dissapear as i uncheck the box?
Dim total As Double
If rb_s1.Checked = True Then
total += 650.0
txt_1.Text = total
thats my code.
and i have many combo boxes, how can i make them all add up as i check/uncheck them.
I would add this functionality into the CheckBox_Changed event handler. This way you can tell if it is unchecked or checked and add or subtract the value from price.
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
total += 650.00
Else
total -= 650.00
End If
TextBox1.Text = total.ToString()
End Sub
You have to use Checked_Changed event of checkbox.
SHARED void CheckBox1_CheckedChanged(object sender, EventArgs e)
IF ChkBx.Checked = true then
textBox1.text = "1500"
else
textBox1.text = ""
END IF
END SUB
To get your displayed text to change when the state of your checkbox changes, you'll need to handle the CheckedChanged event. In Visual Studio while in Desginer mode for your form/control, you can select the check box control, and then in the Properties window, select the Events tab (the one with the little lightingbolt icon), and double click the CheckChanged event to stub in an event handler method AND attach the event to the handler.
ETA: I re-reading this, I'm not sure how clear I was. When I mentioned stubbing in the event handler and attaching the event to the handler, I meant that going the route of double-clicking the event in the designer will do this for you.
As an aside, it sounds like you want the text to be a sum of only the checked items, so from an architechtueral sense, I would recommend creating a single method to determine the sum, and have all check-box check events invoke that method rather than trying to make the event handler method itself do too much directly (maybe that was already clear to you).
So you might do something like this:
Public Class Form1
Private Sub DisplayTotal()
Dim total As Decimal = 0
If (CheckBox1.Checked) Then
total += Decimal.Parse(txtItem1.Text)
End If
'Add other items
txtTotal.Text = total
End If
End Sub
Private Sub CheckBox1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBox1.CheckedChanged
DisplayTotal()
End Sub
Private Sub CheckBox2_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBox1.CheckedChanged
DisplayTotal()
End Sub
End Class

How to create Control Arrays in VB .NET

In VB6 there is a feature called Control Arrays, where you name controls the same name and provide them an index value. This allows you to set a value by looping through the controls and setting each value. In VB .NET I can't create a control array could someone provide me with a similar solution.
Here is a sample I wrote for something else that shows how to do something similar and shows how to do the handler as well. This makes a 10x10 grid of buttons that turn red when you click them.
Dim IsCreated(99) As Boolean
Dim Buttons As New Dictionary(Of String, Button)
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For i As Integer = 0 To 99
Dim B As New Button
Me.Controls.Add(B)
B.Height = 30
B.Width = 40
B.Left = (i Mod 10) * 41
B.Top = (i \ 10) * 31
B.Text = Chr((i \ 10) + Asc("A")) & i Mod 10 + 1
Buttons.Add(B.Text, B)
B.Tag = i
AddHandler B.Click, AddressOf Button_Click
Next
End Sub
Private Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim B As Button = sender
IsCreated(B.Tag) = True
B.BackColor = Color.Red
End Sub
Avoid using the proposed iteration approaches, you'll get a fairly random collection of controls unless your form is very simple. Simply declare the control array in your code and initialize it in the form constructor. Like this:
Public Class Form1
Private OrderNumbers() As TextBox
Public Sub New()
InitializeComponent()
OrderNumbers = New TextBox() {TextBox1, TextBox2}
End Sub
End Class
You can now treat OrderNumbers just like you could in VB6.
Maybe this is simpler. To create a control array, I put the control array declaration in a module. For example, if I have a Form with three TextBoxes and I want the TextBoxes to be part of a control array called 'mytext', I declare my control array in a module as follows:
Module Module1
Public mytext() As TextBox = {Form1.TextBox1, Form1.TextBox2, Form1.TextBox3}
End Module
And, I use the TextBoxes from the control array as follows:
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
mytext(0).Text = "Hello"
mytext(1).Text = "Hi"
mytext(2).Text = "There"
End Sub
End Class
You can even loop through the control array, like you could in VB6:
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
For i As Integer = 0 To 2
mytext(i).Text = i + 1
Next
End Sub
End Class
The beauty of using a module is that the TextBoxes do not even need to be in the same form.
With Winforms, you could do this:
myForm.Controls _
.OfType(Of TextBox) _
.OrderBy(Function(c) c.Name) _
.Where(Function(c) c.Name.StartsWith("somePrefix")) _
.ToArray()
On your form you would name your textboxes somePrefix1, somePrefix2, etc.
Here is an old article but it could give you more information. The top method is super easy.
Your Form, or PanelControl, or anything else that can contain child controls will have a Property called Controls.
You can loop through all of the text boxes in a control by using
'Create a List of TextBoxes, like an Array but better
Dim myTextBoxControls As New List
For Each uxControl As UserControl in MyFormName.Controls
If TypeOf(uControl) is TextBox
myTextBoxControls.Add(uControl)
End IF
Next
Now you have your iterate-able collection you can work with.
You can access a TextBoxes value with the EditValue property.
After looking at what you're trying to do a little further.
You probably want to name all of your controls with a Prefix, let's say abc for now.
For Each uxControl As UserControl in MyFormName.Controls
If TypeOf(uControl) is TextBox Then
Dim tbControl As TextBox = DirectCast(uControl, TextBox)
If tbControl.Name.StartsWith("abc") Then
tbControl.EditValue = "the Value you want to initialize"
End If
End If
Next
So this is one of the features that did not make the transition to VB.NET -- exactly :-( However, you can accomplish much of what you would have done in VB6 with two different mechanisms in .NET: Looping through the controls collection and handling control events.
Looping Through the Controls Collection
In VB.NET every form and control container has a controls collection. This is a collection that you can loop through and then do an operation on the control like set the value.
Dim myTxt As TextBox
For Each ctl As Control In Me.Controls
If TypeOf ctl Is TextBox Then
myTxt = CType(ctl, TextBox)
myTxt.Text = "something"
End If
Next
In this code sample you iterate over the controls collection testing the type of the returned object. If you find a textbox, cast it to a textbox and then do something with it.
Handling Control Events
You can also handle events over multiple controls with one event handler like you would have using the control array in VB6. To do this you will use the Handles keyword.
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged, TextBox3.TextChanged
Dim myTxt As TextBox = CType(sender, TextBox)
MessageBox.Show(myTxt.Text)
End Sub
The key here is the Handles keyword on the end of the event handler. You separate out the various controls that you want to handle and the event by using a comma. Make sure that you are handling controls that have the same event declaration. If you ever wondered what sender was for on every event well here's one of the uses for it. Cast the sender argument to the type of control that you are working with and assign it to a local variable. You will then be able to access and manipulate the control that fired the event just like you would have in VB6 if you specified and index to the array.
Using these two techniques you can replicate the functionality of control arrays in VB6. Good luck.
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim a() As Control = GetControls("textbox")
For Each c As TextBox In a
c.Text = c.Name
Next
End Sub
Private Function GetControls(typeOfControl As String) As Control()
Dim allControls As New List(Of Control)
'this loop will get all the controls on the form
'no matter what the level of container nesting
'thanks to jmcilhinney at vbforums
Dim ctl As Control = Me.GetNextControl(Me, True)
Do Until ctl Is Nothing
allControls.Add(ctl)
ctl = Me.GetNextControl(ctl, True)
Loop
'now return the controls you want
Return allControls.OrderBy(Function(c) c.Name). _
Where( _
Function(c) (c.GetType.ToString.ToLower.Contains(typeOfControl.ToLower) AndAlso _
c.Name.Contains("Box")) _
).ToArray()
End Function

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