Object reference not set to an instance of an object [VB.NET] - vb.net

Public Class Form1
Private Function AllEnabled(ByVal b As Boolean) As Boolean
For i As Integer = 0 To 2
Dim c As CheckBox = CType(Me.Controls("CheckBox" & i.ToString), CheckBox)
c.Enabled = b
Next
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call AllEnabled(False)
End Sub
End Class
getting error with highlight in b at c.Enabled = b
(Object reference not set to an instance of an object.)
but when i use checkbox1.enabled = b instead of c.enabled = b works fine.
so as i see the wrong not with b right ?
& how can i fix this ?

Try this:
For Each ctl In Me.Controls
If TypeOf ctl Is CheckBox Then
ctl.Enabled = b
End If
Next

Two possible reasons. Your for-loop creates this control names:
"CheckBox0"
"CheckBox1"
"CheckBox2"
Maybe you want 1-3 or 0-1 instead.
Maybe you want to find your checkbox recursively, then you can use Find:
For i As Integer = 0 To 2
Dim ctrl = Me.Controls.Find("CheckBox" & i.ToString, True)
If ctrl.Length <> 0 Then
ctrl(0).Enabled = b 'Find returns an aray'
End If
Next
Side-note: 2013 i would not use this VB6 style anymore:
Call AllEnabled(False)
but just
AllEnabled(False)

Related

Is there an option for changing boolean variables trough a loop in vb.net

I am trying to change different values in a for loop in vb.net. However, I couldn't find how to change the numbered boolean variables.
Dim txt1 As Boolean = False
Dim txt2 As Boolean = False
i = i + 1
If i < 9 Then
'I tried to do:
Me.Controls("txt" & i.ToString) = True
txt(i) = True
End If
How can I change the numbered boolean variables and what is the most efficient way to it?
The right way to access the booleans is in an array or a list.
Using the example of the question:
Dim bool(2) As Boolean
i = i + 1
If i < 9 Then
bool(i) = True
End If
I guess you want to iterate over the TextBox controls and then change the property of TextBox.enabled.
You can try the following methods.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each c As Control In Me.Controls
If c.GetType.ToString() = "System.Windows.Forms.TextBox" Then
c.Enabled = True 'You can change the TextBox Controls. Enabled to False too.
c.Text = c.Name.ToString
End If
Next
End Sub

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.

Loop Combobox and variable inside

I have this code:
Dim val1,val2,val3,val4,val5, ... ,val20 As String
If Combobox1.SelectedIndex = 0 Then
val1=">"
else
val1="<"
end if
If Combobox2.SelectedIndex = 0 Then
val2=">"
else
val2="<"
end if
How can I loop this? There are 20 Combo boxes. Please help! Thanks
To loop through the controls on the form, use Me.Controls. And to check the type of the control, use Control.GetType.Name.
The problem is that separate variables like val1,val2,val3...etc cannot be easily used in a loop, so I recommend changing them to a list.
Dim val As New List(Of String)
For Each MyControl In Me.Controls
If MyControl.GetType.Name = "ComboBox" Then
Dim MyComboBox As ComboBox = CType(MyControl, ComboBox)
If MyComboBox.SelectedIndex = 0 Then
val.Add(">")
Else
val.Add("<")
end if
End If
Next
So, here are some looping sequences for you. disclaimer - code is not tested, could be bugs but logical layout should be correct
Private _numOfControls As Integer = 20
Private _variables As New Dictionary(Of String, String)(_numOfControls)
Private Sub Setup()
For i as integer = 1 To _numOfControls
Dim cboName As String = "cbo" & i
Dim cbo As New ComboBox()
cbo.Name = cboName
cbo.SelectedIndex = 0
' Add cbo location according to your logic here
container.Controls.Add(cbo) ' container - any control or form that hosts cbo
_variables.Add(cboName, ">")
AddHandler cbo.SelectedIndexChanged, AddressOf OnCboSelectedIndexChanged
Next
End Sub
' If you do this way, your control-related variable will have appropriate equality sign without need for iteration
Private Sub OnCboSelectedIndexChanged (sender As Object, e As EventArgs)
Dim cbo As ComboBox = CType(sender, ComboBox)
myDict(cbo.Name) = If(cbo.SelectedIndex = 0, ">", "<")
End Sub
' But if you do not want to do in the above^^ way, you can iterate dictionary
Private Sub FromDictionaryToCbo()
' Here you can't use for-loop on dictionary because your dictionary will be mutating. So lets iterate keys
For Each k As String In _variables.Keys.ToArray())
_variables(k) = If(CType(container.Find(k, True), ComboBox).SelectedIndex = 0, ">", "<")
Next
End Sub
' And iterating combo boxes would be something similar as another answer here
' But we use our naming convention to bypass other controls
Private Sub FromCboToDictionary()
Dim c As Control
For i As Integer = 1 To < _numOfControls
Dim key As String = "cbo" & i.ToString()
'We don't know, may be there some other combo boxes are there, so we use our naming convention instead of control type
c = container.Find(key, True)
If c IsNot Nothing Then
_variables(key) = If(CType(c, ComboBox).SelectedIndex = 0, ">", "<")
end If
Next
End Sub

VB, Pass variables to a control

I have been tasked with creating a cinema booking system in VB.net by my teacher. So far I have created 50 CheckBoxes and I am trying to rename them all to seat (number). I have this code in my Form1.load but it is not working because it is a type and not an expression. I tried using a variable for this but it did not work.
Here is my code:
For count As Integer = 1 To 54 Step 1
CheckBox(count).text = "Seat " & count
Next
Please help, and or recommend me another way to accomplish this.
set the name of the checkbox when you create it. To find out how to create a checkbox programmatically add a checkbox to a form then look at .designer.vb
dim cb as new checkbox
cb.name = "1"
cb.text = "Seat 1"
you need to also add the location and other properties
If you have already created your textboxes with names like 1, 2 then iterate through and get the numbers like this: If you call them CB_1 then cut the CB_ off before looking for the number.
dim cbNumber as int16
For Each c As Control In myContainer.Controls
If c.GetType() Is GetType(CheckBox) Then
cbnumber = cint(c.name)
c.text = "Seat" & cbnumber
End If
Next
Well, here's my approach. In order to test just drop on a FlowLayoutPanel, a Button, and a NumericUpDownonto the form.
Option Strict On
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For count As Integer = 1 To 54 Step 1
' Make a new CheckBox
Dim chkBox As New CheckBox()
' Setup the Checkbox
With chkBox
.Tag = count.ToString
.Name = CStr("seatCheckBox" & count.ToString)
.Text = String.Format("Seat {0}", count)
.ThreeState = False
.Checked = False
End With
' add an event listener for the checkbox checkstate changed event
AddHandler chkBox.CheckStateChanged, AddressOf Me.CheckBox_CheckStateChanged
' Add the checkbox to the control
Me.FlowLayoutPanel1.Controls.Add(chkBox)
' Keep the user from picking something that doesn't exist
Me.NumericUpDown1.Maximum = CDec(count)
Next
' Add and event listener for the find button click event
AddHandler Button1.Click, AddressOf Me.FindButton_Clicked
End Sub
' Find the checkbox in the form and return it
Private Function GetCheckBox(ByVal seatNumber As Integer) As CheckBox
Dim chkbox As CheckBox
' Try to find the Checkbox
Try
chkbox = TryCast(Me.Controls.Find(CStr("seatCheckBox" & seatNumber.ToString), True).First, CheckBox)
Catch ex As Exception
chkbox = Nothing
End Try
'Check if the trycast worked
If IsNothing(chkbox) Then
Throw New ArgumentOutOfRangeException("seatNumber", "The seat number to be searched for was not found")
Else
Return chkbox
End If
End Function
' Handle the Chekbox checkState event.
Private Sub CheckBox_CheckStateChanged(sender As Object, e As EventArgs)
' Convert to Checkbox
Dim chkBox As CheckBox = DirectCast(sender, CheckBox)
' Simple result string
Dim resultstring As String = CStr("Seat Number {0} is now {1}.")
' Set the values
Select Case chkBox.Checked
Case True
resultstring = String.Format(resultstring, chkBox.Tag, "taken")
Case False
resultstring = String.Format(resultstring, chkBox.Tag, "available")
End Select
' Display it
MsgBox(resultstring)
End Sub
Private Sub FindButton_Clicked(sender As Object, e As EventArgs)
Try
' Get the checkbox and return it's name
MsgBox(GetCheckBox(CInt(Me.NumericUpDown1.Value)).Name.ToString)
Catch ex As Exception
' Display the error
MsgBox(ex.Message)
End Try
End Sub
End Class

vb.net cycle through controls not working

I'm trying to cycle through the controls on a page that consists of textboxes and a dropdown and clear them.
When I debug, parent is the current page, value is equal to ASP.nameOfCurrentpage_aspx and
Type is equal to system.web.ui.page, but c has the value of ASP.site_master and type of system.web.ui.control. I also put in x to see how many controls it finds and x comes back as 1 even though there are 15 or so textboxes on the page. Is there a way I can force c to have the value of ASP.nameOfCurrentpage_aspx? Or is that not my problem? Any help is appreciated.
Protected Sub btnClear_Click(sender as Object, e as System.eventargs) Handles btnClear.Click
ClearForm(Page)
End Sub
Public Sub ClearForm(ByRef Parent As Control)
Dim c As Control
Dim x As Integer = Parent.Controls.Count
For Each c In Parent.Controls
If c.GetType.ToString = "System.Web.UI.HtmlControls.HtmlForm" Then
ClearForm(c)
ElseIf c.GetType() Is GetType(TextBox) Then
'is it a Text Box?
Dim t As TextBox = c
t.Text = ""
ElseIf c.GetType() Is GetType(DropDownList) Then
'is it a dropdown list?
Dim d As DropDownList = c
d.ClearSelection()
End If
Next
End Sub
The HTMLForm Control is probably nested, likely under a MasterPage. Either go fully recursive with your function or add a clause in your If Statement that looks for the Master Page. This is where breakpoints and the Watch Window are gold.
Ex:
ElseIf c.GetType.ToString = "ASP.MasterPageName_Master" Then
ClearForm(c)
Thank you every for your help. I didn't try all of the answers but I used them for ideas. This is what we came up with at work and it finds and clears all the controls on the page. We had to find the content place holder linked to the master site (cph). Again thanks for all the suggestions.
Public Sub ClearForm(ByRef Parent As Control)
Dim cph As System.Web.UI.WebControls.ContentPlaceHolder = Master.FindControl("MainBody")
Dim c As Control
Dim x As Integer = Parent.Controls.Count
For Each c In cph.Controls
If c.GetType.ToString = "System.Web.UI.HtmlControls.HtmlForm" Then
ClearForm(c)
ElseIf c.GetType() Is GetType(TextBox) Then
'is it a Text Box?
Dim t As TextBox = c
t.Text = ""
ElseIf c.GetType() Is GetType(DropDownList) Then
'is it a dropdown list?
Dim d As DropDownList = c
d.ClearSelection()
End If
Next
End Sub
It's been a while since I programmed anything in .NET with controls, MVC has spoiled me silly, or using VB.NET...
However I am thinking you will probably need to recurse through the stack of controls:
Protected Sub btnClear_Click(sender as Object, e as System.eventargs) Handles btnClear.Click
ClearForm(Page)
End Sub
Public Sub ClearForm(ByRef Parent As Control)
Dim c As Control
Dim x As Integer = Parent.Controls.Count
For Each c In Parent.Controls
If c.GetType.ToString = "System.Web.UI.HtmlControls.HtmlForm" Then
ClearForm(c)
ElseIf c.GetType() Is GetType(TextBox) Then
'is it a Text Box?
Dim t As TextBox = c
t.Text = ""
ElseIf c.GetType() Is GetType(DropDownList) Then
'is it a dropdown list?
Dim d As DropDownList = c
d.ClearSelection()
ElseIf c.Controls != null ' Does VB.NET support nulls? I forget
ClearForm(c.Controls)
End If
Next
End Sub