How to check if a textbox is empty VB.Net [duplicate] - vb.net

This question already has answers here:
Check for empty TextBox controls in VB.NET
(7 answers)
Closed 6 years ago.
I want to test if a textbox is empty for validation purposes, rather than using if x = "". Instead I was wondering if there was a better way to do this. Currently I have:
If txtDob Is Nothing Or txtFirst Is Nothing Or txtGender Is Nothing Or txtLast Is Nothing Or txtPostcode Is Nothing Or txtStreetName Is Nothing Or txtStreetNo.Text Is Nothing Then
MessageBox.Show("One or more fields have not been completed")
Return
End If
However, this doesnt seem to work, can someone show me the correct method or another way to do this please?

For example:
If String.IsNullOrEmpty(txtDob.Text) Then
' "Contains Empty value or Null Value"
End If

You could use this:
Dim emptyTextBoxes =
From txt In Me.Controls.OfType(Of TextBox)()
Where txt.Text.Length = 0
Select txt.Name
If emptyTextBoxes.Any Then
MessageBox.Show(String.Format("Please fill following textboxes: {0}",
String.Join(",", emptyTextBoxes)))
End If
Code from Tim Schmelter's answer on Check for empty TextBox controls in VB.NET

You need to check the Text property.
If txtDob.Text = string.Empty Then
With your Code you're checking if the Object of your TextBox is nothing, not the content. As long as the TextBox exists, your condition would return false.

Related

Append Strings and values together to target a form control in VBA

I'm so close to getting this code working, I just need a little push please. I would like to
take the name of a combo box and then add a string to the end, But then get the value of a textbox with that string. This is to create a dynamic function instead of pasting the same code over and over.
Here's what I have so far, after you select something in the dropdown, the data is then pulled to populate the boxes next to it. I have about 8 drop downs so far so that's why I need this to work.
'Combobox after update
Call GrabData(Me, Me.ActiveControl)
Then
Private Sub GrabData(ctl As Control)
'name of ctl/combobox is "Kitchen"
data1 = (ctl.Name & "Size") '"KitchenSize"
'Here is where it all goes wrong
data1.Value = size.value
'size.value is just a textbox for example
End Sub
I can debug this with:
msgbox(data1)
'outputs "KitchenSize"
But I cannot get the value of kitchensize's textbox with data1.value
Error:
Object Required
I have also added Dim As String / Dim As Control.
I will be assigning the variable to some other stuff in this 50 line code I wrote so please don't take the above example as exactly what I intend to do, I just need help appending the ctl.name to a string, then use that to reference another control and so on.
EDIT
For anyone who wants to know, I figured it out.
Dim Ctrl As Control
Dim CtrlName As String
CtrlName = ctl.Name & "Size"
Set Ctrl = Me.Controls(CtrlName)
Ctrl.Value = 'Wherever you want to send the values to
See the edit.
You need to dim it as a string, then use Set Ctrl

Select Textbox using For Loop

Sorry this is weird and silly question but I need a solution of this...
I have 30 textboxes named as Txt1,Txt2,Txt3,...,Txt30
I have to fill textbox as Txt1.text = 0 on button click..
Is there any way like On Button Click
Dim i as Integer
For i = 1 to 30 '----- Possible in string but don't know if possible in textboxes
Txt(i).text = 0
Next
Or I have to write all 30 lines like
Txt1.text = 0
...
Txt30.text = 0
I don't know how this question asked, maybe Question improper.
Thanx in Advance...
If the textboxes are all contained in Controls collection of the Form, then it is really easy to loop over them
For Each(t in Me.Controls.OfType(Of TextBox)())
t.Text = "0"
Of course the advantage of this approach is that you don't have to worry if you add other textboxes to your form. They will be found using the foreach loop without having a fixed top limit.
And, if not all of your textboxes should be included in the loop, then you can simply use the Tag property of the textboxes that you want to use. For example, if you set the Tag property to the string "Y", then you can change the foreach loop to find only the controls with the matching Tag property
For Each t in Me.Controls.OfType(Of TextBox)() _
.Where(Function(x) x.Tag = "Y")
t.Text = "0"
The two solutions above works well if all your textboxes are contained in the same container (Form, GroupBox or Panel), instead, if these textboxes are dispersed in different containers (some in a groupbox, others in a panel etc) then you can build a List(Of TextBox) variable filling it with the textboxes instances and use it when the need arise
Dim myTexts = New List(Of TextBox)() From { Txt1, Txt2, Txt3, ....}
And loop over this variable
You can do as Steve said, but if you have other textboxes that you don't want to edit then there is another way:
For i = 1 to 30
dim found = Me.Controls.Find("Txt" & i, True) '<- the True argument is for recursive search
If Not IsNothing(found) AndAlso found.Length > 0 Then
found(0).Text = "0"
End If
Next
If your textboxes are all in the same control, for example GroupBox, you can do GroupBox.Controls.Find saving CPU resources

VB.Net Textbox Input Text as Variable Name

I wanted to test if I could get this to work: I have two textboxes with IDs Textbox1 and Textbox2. I enter the name of a variable I have stored in my program in Textbox1 and then I enter any value in Textbox2. After clicking on a confirm button I want to have the value of the variable name that I've written in Textbox1 changed to the value I wrote in Textbox2.
Something like this (in pseudocode)
GetVariable(Textbox1.Text) = Textbox2.Text
Is there an easy way to get this done or will I be forced to create other type of functions to get around this kind of problem?
Yes, you can do this using reflection.
dim property = this.GetType().GetProperty(Textbox1.Text)
property.SetValue(this, Textbox2.Text)
This will not work on local variable, but it will work on properties.
Of course the better way would be to just use a Dictionary(of string, string) instead of loose variable. Then you can just write myValues(Textbox1.Text) = Textbox2.Text.
Another example of using Reflection. This will work on Fields or Properties. They can be Public or Private, and you don't have to exactly match the Case:
Try
Dim FI As System.Reflection.FieldInfo = Me.GetType.GetField(TextBox1.Text, Reflection.BindingFlags.IgnoreCase Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic)
If Not IsNothing(FI) Then
FI.SetValue(Me, TextBox2.Text)
Else
Dim PI As System.Reflection.PropertyInfo = Me.GetType.GetProperty(TextBox1.Text, Reflection.BindingFlags.IgnoreCase Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic)
If Not IsNothing(PI) Then
PI.SetValue(Me, TextBox2.Text)
Else
MessageBox.Show(TextBox1.Text, "Field or Property not found!")
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Unable to Set Value")
End Try
Or you can also create a label control at runtime with the value of TextBox1 Text and assign a value according to the Text of TextBox2. This label will be invisible:
Dim MyNewObject As Control
MyNewObject = New Label
MyNewObject.Name = Textbox1.Text
MyNewObject.Text = Textbox2.Text
MyNewObject.Visible = False
Me.Controls.Add(MyNewObject)
And you can use it as a variable in any part of the form. Example to show the value should be as follows:
MsgBox(Me.Controls(Textbox1.Text).Text)

Verify multiple comboboxes/textboxes have value

I have a winform that has about 6 comboboxes and 3 textboxes. I also have a button that takes the values of aforementioned controls and inserts them into SQL. Is there a better way, than a bunch of nested if/then statements, to verify that the controls all have values before inserting the data? This gets ugly very fast. I have tried googling this answer, but I get too many ASPx answers. I will entertain any ideas you may have. I am just trying to find a better way to do this. Thanks for any help.
I think its not too hard.
This code shows error message about the first empty textbox or combobox. But you can easily modify to show error message for all empty comboboxes and textboxes if required.
Private Function ValidateMyControls() As Boolean
Dim allComboBoxes() As ComboBox = {ComboBox1, ComboBox2, ComboBox3} ' add all your comboboxes here
Dim allTextBoxes() As TextBox = {TextBox1, TextBox2, TextBox3} ' add all your textboxes here
Dim emptyTB As TextBox = allTextBoxes.Where(Function(f) f.Text = "").FirstOrDefault
Dim emptyCB As ComboBox = allComboBoxes.Where(Function(f) f.SelectedIndex = -1).FirstOrDefault
If emptyTB IsNot Nothing Then
MessageBox.Show("Please fill value in " & emptyTB.Name)
Return False
ElseIf emptyCB IsNot Nothing Then
MessageBox.Show("Please select a value in dropdown " & emptyCB.Name)
Return False
Else
' All set to go!
Return True
End If
End Function

Visual Basic 2008 - Me.Controls - Textboxes - NULL -

Self taught(in progress) Visual Basic guy here.
I've searched for a clear answer on this, but so far have come up empty handed.
The problem...
I have two comboboxes. The first combobox has 10 options, second combobox has 2 options
I have 10 textboxes, with a name that includes one of the 10 options.
ex 1st textbox name - "txb_Option1Type"
2nd textbox name - "txb_Option2Type" and so on.
I have 2 tabs, with the first 5 text boxes on the 1st tab and last 5 on the 2nd tab.
I thought the following bit of code, upon a button click, would transfer the text of the chosen option in the 2nd combobox to the corresponding textbox...
`
Public Sub TransferTruckToDoorText()
Dim str_ErrorButton As String = cbx_DoorNumber.Text
Dim str_ReplaceSpacesButton As String = str_ErrorButton.Replace(" ", "")
Dim str_Button As String = str_ReplaceSpacesButton
' Null reference error on below line of code
Me.Controls("txb_" & str_Button & "Type").Text = cbx_TruckType.Text
End Sub
`
As noted in the above code, I'm getting a null reference and for the life of me cannot figure out why. I've stepped through the code, and I'm not able to find a NULL or Nothing value that could be making this catch.
Any and all help would be appreciated.
edited for clarity
The Me.Controls collection does not automatically search the child panels.
Try using the Controls.Find method for that, which includes a parameter to search the child control's control collection, too. It returns an array:
Dim c As Control() = Me.Controls.Find("txb_" & str_Button & "Type", True)
If c.Length = 1 Then
c(0).Text = cbx_TruckType.Text
End If
Me.Controls.Item("txb_" & str_Button & "Type")