If else inside a loop in VB.Net - vb.net

The code below shows the event when a button click is fire
Protected Sub btnFinish_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFinish.Click
For i As Integer = 0 To Gridview1.Rows.Count - 1 Step i + 1
Dim TextBox1 As TextBox = DirectCast(Me.Gridview1.Rows(i).FindControl("txtAnswer"), TextBox)
If TextBox1.Text = String.Empty Then
'do something
ElseIf TexBox1 <> String.Empty Then
'do something else
End If
Next
End Sub
The problem here is that the only condition being executed is in the If-statement even if it should execute the ElseIf-statement. Can someone explain why and how can I solve this problem? [EDITED]

a couple of things to note when comparing text/string:
String could be NULL, instead of Empty
use String.IsNULLOrEmpty to check NULL/Empty
String could be WhiteSpace too, use String.IsWhiteSpace to check it
User could enter a few spaces in some cases, if you want to make sure it's correct, use String.Trim to eliminate any unwanted spaces.
normally what I do is: (NOT String.IsNULLOrEmpty(givenText)) AndAlso givenText.Trim.Length <> 0

Related

check the item in listbox - vb.net

I'm trying to do is check first the item in listbox if the value in textbox is already in listbox.
Private Sub txtSS_PreviewKeydown(ByVal sender As Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles txtSS.PreviewKeyDown
If e.KeyCode = Keys.Tab Then
For Each a As String In String.Join(vbCrLf, ListBox1.Items.Cast(Of String))
If txtSS.Text = a Then
MsgBox("It's already barcoded!")
txtSS.Text = ""
End If
Next
If txtMS.Text = txtSS.Text Then
MsgBox("This is already MAIN SERIAL! kindly check your barcoding serial", MsgBoxStyle.Exclamation)
txtSS.Text = ""
txtSS.Select()
Else
ListBox1.Items.Add(txtSS.Text)
txtSS.Clear()
txtSS.Select()
End If
End If
End Sub
But my code is not working.
the 'a' value of my for each is get only the first char of my listbox.
Think about this expression, used with the For Each loop:
String.Join(vbCrLf, ListBox1.Items.Cast(Of String))
The result of the expression is one string. When you use a string with a For Each loop, it doesn't go line by line. Rather, the loop runs for every character in the string, one character at a time, just as you saw. If you want each item in the ListBox, you don't need to use Join() at all:
For Each a As String In ListBox1.Items.Cast(Of String)()
Or I could refactor the whole method to be MUCH shorter and with less nesting:
Private Sub txtSS_PreviewKeydown(ByVal sender As Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles txtSS.PreviewKeyDown
If e.KeyCode <> Keys.Tab Then Exit Sub
If ListBox1.Items.Any(Function(a) txtSS.Text = DirectCast(a, String)) Then
MsgBox("It's already barcoded!")
Else If txtMS.Text = txtSS.Text Then
MsgBox("This is already MAIN SERIAL! Kindly check your barcoding serial.", MsgBoxStyle.Exclamation)
Else
ListBox1.Items.Add(txtSS.Text)
End If
txtSS.Clear()
txtSS.Select()
End Sub
This also fixes another bug in the original code, where the "It's already barcoded!" result didn't exit the method. The next If check would still have run, where the empty string isn't likely to match the main serial number, and so the method would still likely add a blank line to the bottom of the ListBox. That will no longer happen.
While I'm here, I see you're looking at the Tab key and using bar codes. Most barcode readers by default will send a return key (Cr/Lf) at the end of the scanned text. You can add code to handle this, as well, and possibly make things much easier and faster for you users to do repeated scans.
txtSS.Text = "a"
In your editor set option strict to on to see what is wrong in code

Button is not adding text to the beginning of a text box, but at the end

Private Sub plusMinusButton_Click(sender As Object, e As EventArgs) Handles plusMinusButton.Click
If answerBox.Text <> "0" Then
If answerBox.Text.StartsWith("-") Then
answerBox.Text = answerBox.Text.Replace("-", String.Empty)
Else
'answerBox.Text.Reverse()
'answerBox.AppendText("-")
answerBox.Text = answerBox.Text.Insert(0, "-")
'answerBox.Text.Reverse()
End If
End If
End Sub
This code is supposed to make the number in the text box either positive or negative, depending on if there is a "-" in front of the number or not. But, whenever I run this code, and I input any number other than "0" and I click on the plusMinusButton, the result I get in the text box (answerBox) is something like 1- instead of -1. Now, I changed the code to this, and I got the result I wanted:
Private Sub plusMinusButton_Click(sender As Object, e As EventArgs) Handles plusMinusButton.Click
If answerBox.Text <> "0" Then
If answerBox.Text.EndsWith("-") Then
answerBox.Text = answerBox.Text.Replace("-", String.Empty)
Else
answerBox.Text.Reverse()
answerBox.AppendText("-")
'answerBox.Text = answerBox.Text.Insert(0, "-")
answerBox.Text.Reverse()
End If
End If
End Sub
What am I doing wrong?
Try to use a variable to hold the value.
When you add or minus the value, make it with the integer variable, then after the operation you put the value of variable in your textbox

validating alphanumeric input in textbox [VB2010]

im newbie here, im using vb2010, i just need some help guys.
here's my problem.
i want to validate user's input on my textbox, when user input like this "1a1:b2b:3c3", my project should accept it. but when user input like this "1a1b2b3c3", it will show a msgbox that the format must be "XXX:XXX:XXX".thanks for help in advance.
I done up a very quick example for you, more than enough to get you on the right track. I could have done it a different way, but I am sure this will get you going. I used MaxLength to determine that the user input at least 9 characters and if not let them know. I also made a function that passes the textbox's text into this and will go ahead and format it for you; saves the user time... besides we just need to make sure user primarily enters at least 9 characters anyways if I am correct... Good Luck!
Public Class Form1
Private strValidatedText As String = String.Empty
Private blnValid As Boolean = False
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Make sure user can only enter up to 9 values...
With txtInput
.MaxLength = 9
.TextAlign = HorizontalAlignment.Center
End With
End Sub
Private Sub btnValidate_Click(sender As Object, e As EventArgs) Handles btnValidate.Click
Dim strTextBox As String = txtInput.Text
strValidatedText = ValidateText(strTextBox)
Select Case blnValid
Case True
MessageBox.Show("It's valid! " & strValidatedText)
txtInput.Clear()
txtInput.Focus()
Case Else
MessageBox.Show(strValidatedText)
txtInput.Clear()
txtInput.Focus()
End Select
End Sub
Private Function ValidateText(ByVal strText As String)
Dim strNewText As String = String.Empty
If strText.Length = 9 Then
strNewText = (strText.Substring(0, 3) & ":" & strText.Substring(3, 3) & ":" & strText.Substring(6, 3))
blnValid = True
Else
strNewText = "There must be at least 9 characters in the textbox!"
blnValid = False
End If
Return strNewText
End Function
End Class
Also at that point in the "Select Case blnValid", you can do what ever you would like with that string because it's global...
MrCodeXeR
I would suggest you to use MaskedTextBox class, it will help you to take a formatted input from user. Have a look at this example.
I tried it with following code and it works fine in VB 2010. Just use this code before your variable declaration:
If TextBox1.Text = "" Then 'check if the textbox has a value
MsgBox("Please Enter ID Number")
Return 'will return to the app
ElseIf Not IsNumeric(TextBox1.Text) Then 'check if the entered value is a number
MsgBox("ID Must Be A Number")
Return

Capturing value of DataGridView CheckBox in VB.Net

I have a datagridview (unbound). Fields are Name, Family Name and Phone No and a checkbox colum.
There are ten rows in that DataGridView.
There is an OK button
I need to get message of showing which rows user has checked. The message should appear when user clicks on the OK button. There could be several messages, checking each row one by one, in a loop.
I am not able to get this message. I tried following code in OK button :
Dim strCB As String = dgvChooseQs.Rows(0).Cells(3).Value.ToString
Cell(3) is my checkbox. Do not consider Rows(0), at the moment I am just checking value at row 0
Thanks for your help.
Furqan
Do not use the cell index. Your checkbox column must have a name so you should use it.
Otherwise, what you want to do would be something like this
For each oRow as DataGridViewRow in dgvChooseQs.Rows
If oRow.Cells("ColNamE").Value = True then
'do whatever you need to do.
End if
Next
If you feel you need to cast the column, then you can use CType, but the type is DataGridViewCheckBoxCell, not CheckBox.
You need to do something like this:
if ctype(dgvChooseQs.Rows(0).findcontrol("whateverYourCheckBoxIsNamed"), checkbox).checked then
'throw the message
end if
You may cast the cell value to Boolean, and then check it, as follows:
Dim RowIndex As Integer = ...
Dim ColumnIndex As Integer = ...
Dim IsTicked As Boolean = CBool(DataGridView1.Rows(RowIndex).Cells(ColumnIndex).Value)
If IsTicked Then
MessageBox.Show("You ticked the box.")
Else
MessageBox.Show("You cleared the box.")
End If
Only the third example worked for me but I had to add a Timer
Private Sub DgvElencoFile_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DgvElencoFile.CellClick
'Variabili gestione programma
Dim numerocolonnaSelezionata As Integer
Dim numeroColonnaSelezionataPerDowonload As Integer
Dim numeroRigaSelezionata As Integer
numeroRigaSelezionata = e.RowIndex
NumerocolonnaSelezionata = e.ColumnIndex
If NumeroRigaSelezionata < 0 Then
ClaFunzSgnSon.SegnaleSonoro(ClaFunzSgnSon.EnTipoSgnSon.ErroreImpostazioneDati)
GoTo FineSubFunz
End If
numeroColonnaSelezionataPerDowonload = -1
If DgvElencoFile.Rows(numeroRigaSelezionata).Cells(ClnDownLoad.Name).Selected Then numeroColonnaSelezionataPerDowonload = numerocolonnaSelezionata
If numeroColonnaSelezionataPerDowonload >= 0 Then
TimVisCheckDownLoad.Start()
End If
FineSubFunz:
End Sub
Private Sub TimVisCheckDownLoad_Tick(sender As Object, e As EventArgs) Handles TimVisCheckDownLoad.Tick
TimVisCheckDownLoad.Stop()
Dim isTickedOn = CBool(DirectCast(DgvElencoFile.CurrentCell, DataGridViewCheckBoxCell).EditingCellFormattedValue)
If isTickedOn Then
MessageBox.Show("You ticked the box.")
Else
MessageBox.Show("You cleared the box.")
End If
End Sub
I found a simple solution.
Just change the cell focus after click on cell.
Private Sub DGV_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGV.CellContentClick
If e.ColumnIndex = "Here checkbox column id or name" Then
DGV.Item(e.ColumnIndex, e.RowIndex + 1).Selected = True
'Here your code
MsgBox DGV.Item(e.ColumnIndex, e.RowIndex).Value
End If
End Sub
Don't forget to check if the column of your (ckeckbox + 1) index exist.
Set type of grid in dataGridView to 'DataGridViewCheckBoxXColumn' instead of DataGridViewCheckBoxColumn.
all problems will be solved
The post is old but it can help in need:
You have these three properties after casting your cell:
Private Sub YourDataGridView_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles YourDataGridView.CellMouseClick
Dim b, b1, b2 As Boolean
b = DirectCast(YourDataGridView.CurrentCell, DataGridViewCheckBoxCell).EditingCellValueChanged
b1 = CBool(DirectCast(YourDataGridView.CurrentCell, DataGridViewCheckBoxCell).EditingCellFormattedValue)
b2 = CBool(DirectCast(YourDataGridView.CurrentCell, DataGridViewCheckBoxCell).EditedFormattedValue)
End Sub
it's a long time since this question was sent, but can be useful this answer to anybody with the same issue. In my case, I used (I'm using your notation):
dgvChooseQs.Item(6, vCont).State
where 6 is the checkbox column number, in my case column 6. vCont is an iteration counter in a FOR NEXT loop. If State equals 32, checkbox was checked, else State will be zero. I hope this can be of help.

search through listbox using comma separated values in textbox vb.net 2008

I am writing a code to search through the entire listbox items and highlight them whenever user enters text in textbox. I am looping through textbox items which are entered using a 'comma' . But the code fails to add it to selected indices when user types multiple items using comma. It works fine for single items.
Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
If (e.KeyCode = Keys.Enter) Then
ListBox1.BeginUpdate()
ListBox1.SelectedIndices.Clear()
If TextBox1.Text.Length > 0 Then
Dim lstOfStrings() As String = TextBox1.Text.Split(","c)
For Each s As String In lstOfStrings
For index As Integer = 0 To ListBox1.Items.Count - 1
If s.Trim() <> "" Then
Dim item As String = ListBox1.Items(index).ToString()
If item.IndexOf(TextBox1.Text, StringComparison.CurrentCultureIgnoreCase) >= 0 Then
ListBox1.SelectedIndices.Add(index)
End If
End If
Next
Next s
End
If True Then
End If
End If
ListBox1.EndUpdate()
I think I am missing correct loops or anything else?
Please help.
Thanks.
You are comparing using TextBox1.Text instead of your 'For Each' variable s
The line
If item.IndexOf(TextBox1.Text, StringComparison.CurrentCultureIgnoreCase) >= 0 Then
should be changed to
If item.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) >= 0 Then
Also make sure you Listbox has the property SelectionMode changed to Multi instead of the default of "One"