I have a combobox populated by a datatable, the code searches for a text string located at any position of the field while the user is writing, so far no problem.
So the problem is: When I write the third character the combobox autocompletes with the first result, and there is no way to type anything else.
I have tried already using all AutocompleteMode & AutocompleteSourse properties settings and combinations.
That’s why I’m asking for help.
The code is below:
Private Sub ComboListadoRemitente_KeyUp(sender As Object, e As KeyEventArgs) Handles ComboListadoRemitente.KeyUp
Dim strText As String
strText = ComboListadoRemitente.Text
If Len(strText) > 2 Then
ComboListadoRemitente.DataSource = dtListado.Select("listado LIKE '%" & strText & "%'")
ComboListadoRemitente.DroppedDown = True
Cursor.Current = Cursors.Default
End If
End Sub
Thanks
Finally I got something that works well, it is not the final version, surely can be further improved, here is the code:
Public Sub ComboListadoRemitente_KeyUp(sender As Object, e As KeyEventArgs) Handles ComboListadoRemitente.KeyUp
Dim strText As String
strText = ComboListadoRemitente.Text
If ComboListadoRemitente.Text = "" Then
ComboListadoRemitente.DataSource = Me.dtListado
ComboListadoRemitente.ValueMember = "Id"
ComboListadoRemitente.DisplayMember = "listado"
ComboListadoRemitente.SelectedIndex = -1
ComboListadoRemitente.DroppedDown = False
End If
If Len(strText) > 2 Then
ComboListadoRemitente.DataSource = dtListado.Select("listado LIKE '%" & strText & "%'")
ComboListadoRemitente.ValueMember = "Id"
ComboListadoRemitente.DisplayMember = "listado"
If ComboListadoRemitente.Items.Count <> 0 Then
ComboListadoRemitente.DroppedDown = True
ComboListadoRemitente.SelectedIndex = -1
ComboListadoRemitente.Text = ""
ComboListadoRemitente.SelectedText = strText
strText = ""
Cursor.Current = Cursors.Default
Else
ComboListadoRemitente.DataSource = Me.dtListado
ComboListadoRemitente.ValueMember = "Id"
ComboListadoRemitente.DisplayMember = "listado"
ComboListadoRemitente.SelectedIndex = -1
ComboListadoRemitente.Text = ""
ComboListadoRemitente.SelectedText = strText
strText = ""
ComboListadoRemitente.DroppedDown = False
End If
End If
End Sub
Related
I have a DataGridView (DGV) that I am adding items to from a SQLite DB MANUALLY
My setting for the Selection Mode have been CellSelect and FullRowSelect may have tried others
The Errors and Issues are varied depending on where the user clicks on the DGV
The code as it is now the Errors only occur when an empty Column under Header PID is selected
And when the Column Header PID is selected See Posted Image
I have included the ERRORS as comments in the code
One of the issues I would like to FIX is to disable all sorting on all Columns
The Data added to the DGV is a primary key which is a Integer PID
And some text which is a NVARCHAR(2048) this text is from a RichTextBox
The two biggest issue to fix is preventing the ERRORS YES those are the Questions
Private Sub PopulateDGV()
For Each header As DataGridViewHeaderCell In dgvOne.Rows
'header.SortMode = DataGridViewColumnHeaderCell.NotSortable
Next
'The code Above NOT Working
'ERRORS
'System.InvalidOperationException 'Column's SortMode cannot be set to Automatic
'While the DataGridView control's SelectionMode is set to ColumnHeaderSelect.'
'Your app has entered a break state, but there is no code to show because all
'threads were executing external code (typically system Or framework code).
'dgvOne = DataGridViewColumnSortMode.NotSortable
Dim str2 As String
Dim s1 As Integer
Dim dbName As String = "Word.db"
Dim conn As New SQLiteConnection("Data Source =" & dbName & ";Version=3;")
Dim valuesList As ArrayList = New ArrayList()
'Read from the database
Dim cmd As SQLiteCommand = New SQLiteCommand("Select * FROM ParentTable", conn)
conn.Open()
Dim rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader
'Set Design of the DataGridView
dgvOne.DefaultCellStyle.Font = New Font("Tahoma", 10)
dgvOne.ColumnCount = 2
dgvOne.Columns(0).Width = 60
dgvOne.Columns(1).Width = 420
'Set Col Header Size Mode = Enabled
'Set Col Header Default Cell Styles DO in Properties
dgvOne.ColumnHeadersHeight = 34
'DGV Header Names
dgvOne.Columns(0).Name = "PID"
dgvOne.Columns(1).Name = "Entry Data"
'Read from DB Table add to DGV row
While rdr.Read()
valuesList.Add(rdr(1)).ToString()
lbOne.Items.Add(rdr(1)).ToString()
s1 = rdr(0).ToString
str2 = rdr(1)
dgvOne.Rows.Add(s1, str2)
End While
'Add Blank rows to DGV
For iA = 1 To 4
dgvOne.Rows.Add(" ")
Next
rdr.Close()
conn.Close()
End Sub
Private Sub dgvTwo_CellMouseClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgvOne.CellMouseClick
If (e.RowIndex = -1) Then
MessageBox.Show("No Clicking Here")
Return
End If
If dgvOne.CurrentCell.Value Is Nothing Then
tbMessage.Text = "NO Data Here"
Return
ElseIf e.RowIndex >= 0 Then
tbMessage.Text = e.RowIndex
Dim str2 As String
Dim s2 As String
Dim row As DataGridViewRow = dgvOne.Rows(e.RowIndex)
s2 = row.Cells(0).Value.ToString
str2 = row.Cells(1).Value.ToString
strB = str2
rtbEnter.Text = strB
'ERRORS
'System.NullReferenceException
'HResult = 0x80004003
'Message = Object reference Not Set To an instance Of an Object.
'Source = TestSQL
'StackTrace:
'at TestSQL.frmThree.dgvTwo_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e) in C:\Users\Dwight\source\repos\TestSQL\TestSQL\frmThree.vb:line 117
End If
End Sub
To prevent sorting on columns, which appears to be your main question, do the following:
dgvOne.Columns(0).SortMode = DataGridViewColumnSortMode.NotSortable
dgvOne.Columns(1).SortMode = DataGridViewColumnSortMode.NotSortable
You also need to guard against null values in cells. So in the "CellMouseClick" event, add something like this:
If row.Cells(1).Value IsNot Nothing Then
str2 = row.Cells(1).Value.ToString
End If
#Brian M Stafford
Thanks for getting us headed in the correct direction Vector this is easy to figure out if someone would have shared a little information GREAT Questions's guess your were saving bytes
Because you only have three (3) Columns here are their names and positions in the DGV
Col -1 Col 0 Col 1 and YES they go Left to Right
Just So No One Gets Confused Rows go Top to Bottom
Row 0
Row 1
So all you really needed was one more test that delt with ColumnIndex
This code only permits clicking on Column 1 provided it has text in that CELL
Just manipulate the tests and you can provide the user additional selections
Public Sub dgvTwo_CellMouseClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgvOne.CellMouseClick
If e.RowIndex = -1 Or e.ColumnIndex = -1 Then
'tbMessage.Text = "Col " & e.ColumnIndex & " ROW " & e.RowIndex
tbMessage.Text = "No Clicking Here"
Return
End If
If dgvOne.CurrentCell.Value Is Nothing Then
tbMessage.Text = "NO Data Here"
Return
End If
Dim s3 As Integer
s3 = e.ColumnIndex
If s3 = 0 Then
'tbMessage.Text = "S3 " & e.ColumnIndex
tbMessage.Text = "No Clicking Here"
Return
End If
Dim row As DataGridViewRow = dgvOne.Rows(e.RowIndex)
Dim col As DataGridViewColumn = dgvOne.Columns(e.ColumnIndex)
If e.RowIndex >= 0 And e.ColumnIndex <> -1 Then
tbMessage.Text = "Data Sent to RTB"
Dim str2 As String
str2 = row.Cells(1).Value.ToString
rtbEnter.Text = str2
End If
End Sub
After reading all the nice answers and looking for a way to accomplish my multitude of issues and a lot of trial and error here is one way to deal with preventing the user from clicking on various location on the DataGridView
Public Sub dgvTwo_CellMouseClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgvOne.CellMouseClick
If e.RowIndex = -1 Or e.ColumnIndex = -1 Then
'tbMessage.Text = "Col " & e.ColumnIndex & " ROW " & e.RowIndex
tbMessage.Text = "No Clicking Here"
rtbEnter.Clear()
Return
End If
Dim str1 As String
Dim str2 As String
Dim s1 As Integer
Dim row As DataGridViewRow = dgvOne.Rows(e.RowIndex)
str1 = dgvOne.CurrentRow.Cells(0).Value.ToString
If str1 IsNot " " Then
If str1 Is " " Then
Return
End If
tbMessage.Text = "Text Sent to RTB"
s1 = row.Cells(0).Value
'Dim strInt As String
gv_passInt = s1.ToString
str2 = row.Cells(1).Value.ToString
rtbEnter.Text = str2
gv_passStr = str2
Return
End If
rtbEnter.Clear()
tbMessage.Text = "No Data Here"
End Sub
I have created a service that is supposed to pass data from SQL to CSV, by creating a CSV file. It has no errors, but i run it and nothing happens.
1) Is there something I am missing?
2) If it works, and i want to convert to txt file, is it enough to change the "CSV" to "txt" parts?
My code:
#Region "Export SQL TO CSV"
Public Shared Function WriteCSV(ByVal input As String) As String
Try
If (input Is Nothing) Then
Return String.Empty
End If
Dim containsQuote As Boolean = False
Dim containsComma As Boolean = False
Dim len As Integer = input.Length
Dim i As Integer = 0
Do While ((i < len) _
AndAlso ((containsComma = False) _
OrElse (containsQuote = False)))
Dim ch As Char = input(i)
If (ch = Microsoft.VisualBasic.ChrW(34)) Then
containsQuote = True
ElseIf (ch = Microsoft.VisualBasic.ChrW(44)) Then
containsComma = True
End If
i = (i + 1)
Loop
If (containsQuote AndAlso containsComma) Then
input = input.Replace("""", """""")
End If
If (containsComma) Then
Return """" & input & """"
Else
Return input
End If
Catch ex As Exception
Throw
End Try
End Function
Private Sub ExtoCsv(ByVal sender As Object, ByVal e As EventArgs)
Dim sb As StringBuilder = New StringBuilder
Using db As Database.RecordSet = admin.Database.OpenRecordsetReadOnly("select USERID, NAME1 from usertable WHERE I_ID=2")
Dim userid As String = db("USERID").Value
Dim name1 As String = db("NAME1").Value
For i As Integer = 1 To db.RecordCount
sb.Append(WriteCSV(userid + "," + name1 + ","))
sb.AppendLine()
db.MoveNext()
Next
End Using
File.WriteAllText("C:\Users\user1\Desktop\ex1.csv", sb.ToString)
If (Not System.IO.Directory.Exists("C:\Users\user1\Desktop\ex1")) Then
System.IO.Directory.CreateDirectory("C:\Users\user1\Desktop\ex1")
End If
End Sub
#End Region
So, I am making a console in VB.net. I decided to use, in a Lua type fashion, a sub string way. However, when doing this, if I type something that is not a command, then it will crash with the error: "Additional information: Index and length must refer to a location within the string."
Public Class Form1
Private Sub TextBox2_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox2.KeyDown
Dim cmd As String = TextBox2.Text
Dim l As Integer = Len(TextBox2.Text)
Dim param As String
If e.KeyCode = Keys.Enter Then
'0 Param command
If cmd = "script" Then
Script.Show()
TextBox2.Text = ""
'Trying to avoide error "Additional information: Index and length must refer to a location within the string."
ElseIf Not cmd.Substring(0, 5) = "echo;" Or Not cmd.Substring(0, 9) = "download;" Then
Return
'1 Param cmd
ElseIf cmd.Substring(0, 5) = "echo;" Then
param = cmd.Substring(5)
Me.TextBox1.Text = Me.TextBox1.Text + Environment.NewLine + param
TextBox2.Text = ""
'2 Param cmd
ElseIf cmd.Substring(0, 9) = "download;" Then
param = cmd.Substring(9)
Me.TextBox1.Text = Me.TextBox1.Text + Environment.NewLine + param.Substring(0, param.IndexOf(";"c)) + param.Substring(param.IndexOf(";"c) + 1)
TextBox2.Text = ""
End If
End If
End Sub
End Class
You cannot try to get a substring from locations that are not inside the string.
However instead of trying to get a substring you could use a simpler approach that avoid also the first check on the input text
If cmd = "script" Then
.....
ElseIf cmd.StartsWith("echo;") Then
.....
ElseIf cmd.StartsWith("download;") Then
....
Else
Return
End If
Hello I am currently making an hangman game where you guess a randomly selected word and you have three rounds. Each time you win a round you gain 10 points, however if you don't guess the word before you run out of the 10 generous attempts. You will lose the round not gain anything.
After you win you three games of hangman, you are shown a new input text box in a high score form to input your name to save your high score to be displayed on the high score form and it has validation in (Meaning the user is required have at least one character inside the text box). This is where my main problem is, my input box will save your name and your points if you pass validation first time. However if you didn't pass validation first time but pass it the second time, your name is saved however your high score will be saved but only with one point. Sorry for my bad English, but is there anyway to keep the amount of points the user scores even if they failed validation first time instead of changing it to 1 point? Here is my code (Sorry for the bad indention):
Hangman Game Code (This is where the user gets their points from)
Imports System.IO
Public Class Hangman
'Public Variables
Public AttemptsLeft As Integer = 0
Public Rounds As Integer = 1
Public LetterChosen As Char
Dim EndWord() As Char
Dim AppPath As String = Application.StartupPath()
Dim FileRead() As String
Public GameWinner As Boolean = True
Dim HangmanShapes As New List(Of PowerPacks.Shape)
Public ScoreForRound As Integer
Dim NewControls As New List(Of Button)
Dim GameWord As New List(Of Label)
'Form Load code
Private Sub Hangman_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Load Word Game Code
If File.Exists(AppPath & "/wordlist.txt") Then
FileRead = IO.File.ReadAllLines(AppPath & "/wordlist.txt")
Dim RandomWord As New List(Of String)
For i = 0 To FileRead.Length - 1
RandomWord.Add(FileRead(i))
Next
Dim random As New Random() 'Using this to randomise each word
EndWord = RandomWord(random.Next(0, RandomWord.Count - 1)).ToUpper.ToCharArray 'Will put each character of the randomly chosen word into the labels.
Score.Text = UScore
Round.Text = Rounds
Letter1.Text = EndWord(0)
Letter1.Visible = False
Letter2.Text = EndWord(1)
Letter2.Visible = False
Letter3.Text = EndWord(2)
Letter3.Visible = False
Letter4.Text = EndWord(3)
Letter4.Visible = False
Letter5.Text = EndWord(4)
Letter5.Visible = False
Letter6.Text = EndWord(5)
Letter6.Visible = False
'Attempts left code
End If
With HangmanShapes
.Add(Attempt1)
.Add(Attempt2)
.Add(Attempt3)
.Add(Attempt4)
.Add(Attempt5)
.Add(Attempt6)
.Add(Attempt7)
.Add(Attempt8)
.Add(Attempt9)
.Add(Attempt10Part1)
.Add(Attempt10Part2)
End With
With NewControls
.Add(LetterA)
.Add(LetterB)
.Add(LetterC)
.Add(LetterD)
.Add(LetterE)
.Add(LetterF)
.Add(LetterG)
.Add(LetterH)
.Add(LetterI)
.Add(LetterJ)
.Add(LetterK)
.Add(LetterL)
.Add(LetterM)
.Add(LetterN)
.Add(LetterO)
.Add(LetterP)
.Add(LetterQ)
.Add(LetterR)
.Add(LetterS)
.Add(LetterT)
.Add(LetterU)
.Add(LetterV)
.Add(LetterW)
.Add(LetterX)
.Add(LetterY)
.Add(LetterZ)
End With
With GameWord
.Add(Me.Letter1)
.Add(Me.Letter2)
.Add(Me.Letter3)
.Add(Me.Letter4)
.Add(Me.Letter5)
.Add(Me.Letter6)
End With
End Sub
Private Sub AllBtnClicks(ByVal sender As System.Object, ByVal e As EventArgs) Handles LetterA.Click, LetterB.Click, LetterC.Click, LetterD.Click, LetterE.Click, LetterF.Click, LetterG.Click, LetterH.Click, LetterI.Click, LetterJ.Click, LetterK.Click, LetterL.Click, LetterM.Click, LetterN.Click, LetterO.Click, LetterP.Click, LetterQ.Click, LetterR.Click, LetterS.Click, LetterT.Click, LetterU.Click, LetterV.Click, LetterW.Click, LetterX.Click, LetterY.Click, LetterZ.Click
'Declartions
Dim LetterGuess As Button = sender
LetterGuess.Enabled = False
Dim LetterCorrect As Boolean = False
'Loop
For Each Letter In EndWord
If GetChar(LetterGuess.Name, 7) = Letter Then
Select Case Array.IndexOf(EndWord, Letter)
Case Is = 0
Letter1.Visible = True
Case Is = 1
Letter2.Visible = True
Case Is = 2
Letter3.Visible = True
Case Is = 3
Letter4.Visible = True
Case Is = 4
Letter5.Visible = True
Case Is = 5
Letter6.Visible = True
End Select
LetterCorrect = True
End If
Next
'Lives left code
If LetterCorrect = False Then
AttemptsLeft += 1
Select Case AttemptsLeft
Case 1
Attempt1.Visible = True
Attempts.Text = 1
Case 2
Attempt2.Visible = True
Attempts.Text = 2
Case 3
Attempt3.Visible = True
Attempts.Text = 3
Case 4
Attempt4.Visible = True
Attempts.Text = 4
Case 5
Attempt5.Visible = True
Attempts.Text = 5
Case 6
Attempt6.Visible = True
Attempts.Text = 6
Case 7
Attempt7.Visible = True
Attempts.Text = 7
Case 8
Attempt8.Visible = True
Attempts.Text = 8
Case 9
Attempt9.Visible = True
Attempts.Text = 9
Case 10
Attempt10Part1.Visible = True
Attempt10Part2.Visible = True
Attempts.Text = 10
LetterA.Enabled = False
LetterB.Enabled = False
LetterC.Enabled = False
LetterD.Enabled = False
LetterE.Enabled = False
LetterF.Enabled = False
LetterG.Enabled = False
LetterH.Enabled = False
LetterI.Enabled = False
LetterJ.Enabled = False
LetterK.Enabled = False
LetterL.Enabled = False
LetterM.Enabled = False
LetterN.Enabled = False
LetterO.Enabled = False
LetterP.Enabled = False
LetterQ.Enabled = False
LetterR.Enabled = False
LetterS.Enabled = False
LetterT.Enabled = False
LetterU.Enabled = False
LetterV.Enabled = False
LetterW.Enabled = False
LetterX.Enabled = False
LetterY.Enabled = False
LetterZ.Enabled = False
MsgBox("You have lost the round!")
ResetForm(0)
End Select
'Winning a round code
Else : Dim GameWinner As Boolean = True
Dim WordCheck As Label
For Each WordCheck In GameWord
If Not WordCheck.Visible Then
GameWinner = False
Exit For
End If
Next
If GameWinner Then
MsgBox("You have won the round!")
ResetForm(10)
'Losing a round code
End If
End If
End Sub
Private Sub ResetForm(ScoreForRound As Integer)
UScore += ScoreForRound
If Rounds = 3 Then
Me.Close()
HighScore.Show()
Else
Score.Text = +10
AttemptsLeft = 0
Attempts.Text = 0
Rounds += 1
Hangman_Load(Nothing, Nothing)
Dim HangmanReset As PowerPacks.Shape
For Each HangmanReset In HangmanShapes
HangmanReset.Visible = False
Next
Dim ControlReset As Control
For Each ControlReset In NewControls
ControlReset.Enabled = True
Next
End If
End Sub
End Class
High score form (This is where the user saves their points and also be able to view their high scores afterwards)
Imports System.IO
Public Class HighScore
Dim AppPath As String = Application.StartupPath()
Public Username As String
Private Sub HighScore_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim FileData() As String
Dim SizeArray As Integer
Try
FileData = File.ReadAllLines(AppPath & "/highscore.txt")
SizeArray = FileData.Length
Catch Break As Exception
MsgBox("The file is missing!", MsgBoxStyle.Critical)
End Try
For begin = 0 To SizeArray - 1 Step 1
Me.UserNameLabel.Text = UserNameLabel.Text & FileData(begin) & vbNewLine
Next
End Sub
Private Sub Backtomainmenu_Click(sender As Object, e As EventArgs) Handles Backtomainmenu.Click
MainMenu.Visible = True
Me.Visible = False
End Sub
Private Sub HelpButtonHighScore_Click(sender As Object, e As EventArgs) Handles HelpButtonHighScore.Click
MsgBox("This is the high score, this shows the top 10 players who achieved well in this game, this is ranked by the amount of points score. If you want to have your name in this high score, play the game well in order to achieve this.", MsgBoxStyle.Information)
End Sub
'This is where the user saves their high scores
Private Sub SaveName_Click(sender As Object, e As EventArgs) Handles SaveName.Click
Username = NameInput.Text
Try
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Catch ex As Exception
MsgBox("The file is missing!", MsgBoxStyle.Critical)
End Try
UScore = vbNull
If NameInput.Text = "" Then
MsgBox("Enter a name please")
Else
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Me.Close()
MainMenu.Show()
End If
End Sub
End Class
the user is required have at least one character inside the text box
Your code is currently saving to the file before any validation occurs:
Username = NameInput.Text
Try
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Catch ex As Exception
MsgBox("The file is missing!", MsgBoxStyle.Critical)
End Try
UScore = vbNull
After that block of code (which has already written to the file), then you're attempting to validate:
If NameInput.Text = "" Then
MsgBox("Enter a name please")
Else
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Me.Close()
MainMenu.Show()
End If
Consolidate the code, and only write to the file if your validation is successful:
Private Sub SaveName_Click(sender As Object, e As EventArgs) Handles SaveName.Click
Username = NameInput.Text.Trim
If Username = "" Then
MsgBox("Enter a name please!")
Else
Try
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
UScore = vbNull
Me.Close()
MainMenu.Show()
Catch ex As Exception
MsgBox("Error Saving High Score File!" & vbCrLf & vbCrLf & ex.ToString(), MsgBoxStyle.Critical)
End Try
End If
End Sub
With UScore = vbNull, you might be resetting the score even if NameInput.Text = "".
So, instead of
Try
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Catch ex As Exception
MsgBox("The file is missing!", MsgBoxStyle.Critical)
End Try
UScore = vbNull
If NameInput.Text = "" Then
MsgBox("Enter a name please")
Else
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Me.Close()
MainMenu.Show()
End If
Put UScore = vbNull inside the If statement so
Try
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Catch ex As Exception
MsgBox("The file is missing!", MsgBoxStyle.Critical)
End Try
If NameInput.Text = "" Then
MsgBox("Enter a name please")
Else
File.WriteAllText(AppPath & "/highscore.txt", Username & " " & UScore)
Me.Close()
MainMenu.Show()
UScore = vbNull 'Put it here instead
End If
I'm able to validate the cells if they are empty but I'm not able to check the length of the cell. I want the user to enter 5 digits and if it is less than 5, show up a message box.
I tried cellvalue.length method but its not working.
Private Sub dgvResults_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles dgvResults.CellValidating
'variables
Dim columnName As String = dgvResults.Columns(e.ColumnIndex).Name
Dim cellVal As String = e.FormattedValue.ToString()
'Datagrid view validation
If ((e.ColumnIndex = 0) And (e.FormattedValue = "") And (Not (cellVal.Length = 5))) Then
e.Cancel = True
MessageBox.Show(columnName & " must be 5 Digits Long!")
ElseIf (e.ColumnIndex = 1 And e.FormattedValue = "") Then
e.Cancel = True
MessageBox.Show(columnName & " cannot be blank!")
ElseIf (e.ColumnIndex = 2 And e.FormattedValue = "") Then
e.Cancel = True
MessageBox.Show(columnName & " cannot be blank!")
ElseIf ((e.ColumnIndex = 3) And (e.FormattedValue = "") And (Not IsNumeric(e.FormattedValue))) Then
e.Cancel = True
MessageBox.Show(columnName & " cannot be blank!")
ElseIf ((e.ColumnIndex = 4) And (Not IsNumeric(e.FormattedValue))) Then
e.Cancel = True
MessageBox.Show(columnName & " cannot be blank!")
End If
End Sub
Following causes your code to not work:
(e.FormattedValue = "") And (Not (cellVal.Length = 5))
You are checking if the value is empty and also it's length is <> 5.
But you want to ensure that cellVal.Length is = 5:
If e.ColumnIndex = 0 AndAlso cellVal.Length <> 5 Then
e.Cancel = True
MessageBox.Show(columnName & " must be 5 Digits Long!")
End If
I think you will need:
cellval.text.length