How would I use a for loop to edit multiple labels in Visual basic for visual studios - vb.net

Here is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim randVal As Integer
Dim label As String
Dim val As Integer
Dim stringVal As String
For i As Integer = 1 To 256 Step 1
val = i
stringVal = CStr(val)
label = "Label" + stringVal
randVal = CInt(Math.Floor((20 - 1 + 1) * Rnd())) + 1
label.BackColor = Color.Green
Next
End Sub
I get an error that string has no property BackColor.
How would I be able to edit all the strings without calling them individually?

The error message is correct: there isn't a property called BackColor on a string.
There is a BackColor property on Button, however, and it looks as if you're perhaps trying to set the background color of the Button object when it's clicked. If so, then you need to get hold of the Button object before you can set the color. The event handler has made this (moderately) easy, by passing the object into your handler as the parameter "sender". The only problem is that it's sent it as an object, not as a Button, so you first have to cast it to the type you want, like this:
Dim button As Button
button = DirectCast(sender, Button)
Then later on you can set the color:
button.BackColor = Color.Green
Also, if you want to set the text of the button, you have to set it using the button.Text property:
button.Text = "What I want to see on the button"
However, you're program is hard to follow. I can't see clearly from the code why you're executing a loop, or why you're setting values like randVal that aren't being used, and so it's hard to give concrete advice.

You are trying to access a property that does not exist.
The String type in Visual Basic has two properties. See here (https://msdn.microsoft.com/en-us/library/system.string_properties(v=vs.110).aspx)
If you are trying to change the background color of your label, then you need to reference your label name, which has that property.
For example: (I am assuming you want to change the text and color on your label)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim randVal As Integer
Dim labelText As String
Dim val As Integer
Dim stringVal As String
For i As Integer = 1 To 256 Step 1
val = i
stringVal = CStr(val)
labelText = "Label" + stringVal
randVal = CInt(Math.Floor((20 - 1 + 1) * Rnd())) + 1
labelName.BackColor = Color.Green
Next
End Sub
Having said that, you can also use your label properties to change the text of your label.
labelName.Text = "Label" + stringVal
Here are some references
(How to change the text color. Simple?)
Also, here is a link to Label Properties (https://msdn.microsoft.com/en-us/library/system.windows.forms.label_properties(v=vs.110).aspx)
and your Buttons properties (https://msdn.microsoft.com/en-us/library/system.windows.forms.button(v=vs.110).aspx)

You managed to set the variable label to the name of your Label control, but not to the object itself. Now you need to get that Control object from its name.
VB6:
Me.Controls(label).BackColor = vbGreen
VB.Net:
Me.Controls(label).BackColor = Color.Green
However, you had an easier way to span you label controls and update their backgrounds:
Dim c as Control
For Each c In Me.Controls
If (TypeOf c Is Label) Then c.BackColor = Color.Green
Next c

If you want to reference Label1 thru Label256 in a loop, no matter which container they are in, then use Controls.Find():
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i As Integer = 1 To 256
Dim lbl As Label = Me.Controls.Find("Label" & i, True).FirstOrDefault
If Not IsNothing(lbl) Then
lbl.BackColor = Color.Green
End If
Next
End Sub

Related

VB How To Select All Controls Of Type And Set Text To Nothing

im coding a sequence guesser game and id like to program it so whenever you enter a number wrong it resets all the labels how would i universally select the label type and make the text = Nothing
i tried this but it didnt work
Thanks
Imports System.Media
Public Class comboForm
Dim score As Integer = 0
Dim winsound As New SoundPlayer(My.Resources.winsound_wav)
' 1 7 8 8 4 7 1 5 5
Private Sub btn1_Click(sender As Object, e As EventArgs) Handles btn1.Click
If score = 0 Then
score += 1
lblStage1.Text = "1"
ElseIf score = 7 Then
score += 1
lblStage7.Text = "7"
Else
score = 0
For Each lbl In tlpMain.Controls.OfType(Of Label)()
lbl.Text = Nothing
Next
End If
End Sub
End Class
For Each lbl In Me.Controls.OfType(Of Label)()
'...
Next
The OfType method is basically a filter by type on a list. That code is pretty much the equivalent of this:
For Each ctrl In Me.Controls
If TypeOf ctrl Is Label Then
Dim lbl = DirectCast(ctrl, Label)
'...
End If
Next
or this:
For Each ctrl In Me.Controls
Dim lbl = TryCast(ctrl, Label)
If lbl IsNot Nothing Then
'...
End If
Next
Obviously this code will only access Labels directly on the form, because it uses the form's Controls collection. Use the Controls collection of the appropriate container, e.g. a Panel to access controls in that container.

Making labels in charts selectable/editable in VB

Just like in excel for a graph you can double click on a title, series name, or axis label and then you are able to type in that space. What do I need to do so I can do that for my charts? Clueless on where to start. Seems I may have to create a custom label?
Use the HitTest method of the chart.
Imports System.Windows.Forms.DataVisualization.Charting
Public Class Form1
Private Sub Chart1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles Chart1.MouseDoubleClick
Dim h As HitTestResult = Chart1.HitTest(e.X, e.Y) 'Perform the HitTest with the mouse position that was clicked
If h.ChartElementType = ChartElementType.AxisTitle OrElse _
h.ChartElementType = ChartElementType.Axis Then 'Check the type of the element of the chart that was clicked
Dim s As String = InputBox("Please enter a new title!", "", h.Axis.Title) 'Prompt for a new title
If s <> "" Then h.Axis.Title = s 'Assign the new title
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i = 1 To 20 'Put some data in the chart to make the axes visible
Chart1.Series(0).Points.AddXY(i, i ^ 2)
Next
End Sub
End Class
You basically use the mouse location for the HitTest method. The ChartElementType defines what element was clicked at the position. If it's the title of the axis or the axis itself it will prompt you with an InputBox for a new title and assigns this title.
The InputBox is pretty old and shouldn't really be used but I was lazy and it works :-)
Apparently, what I'm referring to lives in DataVisualization.Charting.TextAnnotation. Along with that one, are many more type of annotations.
A TextAnnotation allows: AnchorMoving, Moving, PathEditing, Resizing, Selecting, and TextEditing. All of which I'm looking for.
Simple setup:
Dim anno As New DataVisualization.Charting.TextAnnotation
anno.AllowTextEditing = true
anno.AllowSelecting = true
anno.AllowMoving = true
anno.AllowResizing = true
anno.x = 50
anno.y = 50
anno.text = "Your Text"
chart.annotations.add(xAxisAnno)

When creating a label a label inside a panel, the text is cut off VisualBasic

I wanted to be able to dynamically create a panel with a label on it, but the label isn't acting as I would expect it too, its cutting most of it off.
When I create a panel then create a label inside the panel, the text isn't displayed correctly. Anyone know how to fix it?
What is was supposed to do was to create a panel with text on it with the newpanel() sub
Dim timetable(5, 5) As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Width = (74 * 5) - 3
Me.Height = My.Computer.Screen.Bounds.Size.Height
Me.Top = My.Computer.Screen.Bounds.Top
Me.Left = My.Computer.Screen.Bounds.Right - Me.Width
GetTimetable()
End Sub
Private Sub newpanel(colour As Color, textT As String)
Dim Npan As New Panel
Npan.Top = 0
Npan.Left = 0
Npan.Width = Me.Width
Npan.Height = 64
Npan.BackColor = colour
Dim NpanT As New Label
NpanT.Parent = Npan
NpanT.Text = textT
Npan.Controls.Add(NpanT)
Me.Controls.Add(Npan)
End Sub
Private Sub GetTimetable()
'Dim path As String = My.Computer.FileSystem.SpecialDirectories.Desktop + "\Timetable"
newpanel(Color.Aqua, "this is a test! test testtesttest test test test")
End Sub
Looking at the MSDN page for the Label.AutoSize Property, it states as was mentioned above that the Labels AutoSize Property defaults to true in the designer, but it is false when created in code.
From above link:
When added to a form using the designer, the default value is true. When instantiated from code, the default value is false.
So you need to change your newpanel method to this:
Private Sub newpanel(colour As Color, textT As String)
Dim Npan As New Panel
Npan.Top = 0
Npan.Left = 0
Npan.Width = Me.Width
Npan.Height = 64
Npan.BackColor = colour
Dim NpanT As New Label
NpanT.Parent = Npan
NpanT.Text = textT
NpanT.AutoSize = True 'Enables Auto sizing
Npan.Controls.Add(NpanT)
Me.Controls.Add(Npan)
End Sub

Convert a string to

For example i have a program with 10 buttons and when i press a random one its name is saved to a string and i want to add 1 to the button's name for example if i pressed button1 ill alter the string to say button2 but now i cant use that string because it cant convert string to system.windows.forms.buttons, i have already tried the Me.Controls bu it didnt work for me.
Example:
dim stringy as string
dim integr as integer
dim buton as button
sub procedureee
stringy = stringy.remove(0,6)
integr = val(stringy) + 1
stringy = "Button" & integr
button.backcolor = white
end sub
Button1_Click
stringy = button1
procedureee
/* EDIT */
Im sorry i think i didnt make my sefl clear, everything in this code works for me except "stringy = button1" it says that string cannot be converted to system.windows.forms.button but thats exactly what i want to do, i have a program with 100 buttons and when any button is pressed it sets the value of ("Dim local as button") the variable local= the button pressed, and it works so i take that button.name and remove 1 from it so i get the value of the button above(PS: i have the buttons on a grid and vertically its from 1 to 10 and if i remove 1 il get the name of the button abore ex: button1gA3 becomes Button1gA2) but when i try to do this local2 = stringy it gives me that message(string cannot be converted to system.windows.forms.button) anyone knows how to solve this?
Thanks.
Here you go ...
Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.click
Dim FullButtonName As String = sender.text
Dim ButtonsNumber As String = FullButtonName.Replace("Button", "").Trim
Dim NewButtonNumber As Integer = CType(ButtonsNumber, Integer) + 1
sender.text = "Button " & NewButtonNumber.ToString
End Sub
You can use FindControl() to find a control by name. Note that it is not recursive, and so you'll need to call this method on the direct parent that contains your buttons.

Simple VB, handling many buttons

In my VB solution I have a lot of buttons arranged in a grid. When the program is loaded one of the buttons is randomly set to be the right one (You have to click that one to win). Can anybody point my in the right direction? Because there must be a better way than manually coding every single button, and creating an event handler for every single button.
You don't have to give me a working example, just an overall idea of how this is done.
Thanks.
If you want to arrange the buttons in a grid, either use the TableLayoutPanel or add the buttons directly to the form and calculate their positions. The TableLayoutPanel is useful if you want to arrange the buttons automatically when the form resizes, otherwise adding the buttons directly seems easier to me.
Add the buttons to an array defined at form level to make them easily accessible
Public Const NColumns As Integer = 5, NRows As Integer = 4
Private buttons As Button(,) = New Button(NColumns - 1, NRows - 1) {}
You can add the buttons easily in loops
For ix As Integer = 0 To NColumns - 1
For iy As Integer = 0 To NRows - 1
Dim btn = New Button()
btn.Text = String.Format("{0:d2}{1:d2}", ix, iy)
btn.Location = New Point(leftMargin + ix * xDistance,
topMargin + iy * yDistance)
btn.Size = New Size(buttonWidth, buttonHeight)
AddHandler btn.Click, Addressof Button_Clicked
buttons(ix, iy) = btn
Controls.Add(btn)
Next
Next
You can determine the winning button with a random generator. Define it as form member, not as local variable.
Private randomGenrator As System.Random = New System.Random()
Determine the coordinates
Dim xWins = randomGenrator.Next(NColumns) 'Returns a number between 0 and NColumns-1
Dim yWins = randomGenrator.Next(NRows)
The click handler looks like this
Private Sub Button Button_Clicked(sender As Object, e As EventArgs)
If sender = buttons(xWins, yWins) Then
'You win
Else
'You loose
End
End Sub
First, you said you want a grid of buttons, so you have to have a FlowLayoutPanel control in your form in order to let the buttons you want to add, to be arranged automatically.
Second, you have to make use of a for loop, r any kind of look, in order to add the buttons to be added to previously added 'FlowLayoutPanel'.
class Answers
Dim strAnswerText as string
Dim AnswerFlag as Boolean
End Class
Sub LoadForm(byval a_Answers as Answer())
Dim i as Integer = 0
Dim b as Button
For(i=0;i<NUM_OF_BUTTONS;i++)
b = New Button()
b.Text = "Choice -" & i & "- " & a_Answers(i).strAnswerText
b.Tag = a_Answers(i).AnswerFlag
'Supposing that the FlowLayoutPanel control name is fl
AddHandler b.Click, Addressof Clicked
fl.controls.Add(b)
End For
End Sub
Sub Button Clicked(sender as object, e as EventArgs)
if sender.Tag = True
'True answer
else
'Wrong answer
end if
End Sub