compare/check character against an array of chars - best practice?

G

Guest

The procedure below checks if a character entered into a cell of a
datagridview is contained in a string array of valid characters for this
particular cell. It seems kludgy. I am asking what the best practice would
be. I was thinking I could use an arrayList which has the "contains"
property and do this:

If not arr.Contains(s1) then --- don't continue

but my list of codes might be about 50 char combinations. So I was thinking
a string array. But with the string array I can only think of checking the
value using loops in the following kludge procedure

Dim s1 As String, b1 As Boolean
s1 = StrConv(dgrv1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value.ToString,
VbStrConv.Uppercase)
b1 = False
If s1 <> "" Then
Dim arr() As String = New String() {"C", "D", "F", "I", "N", "P", "R", "U"}
For Each str1 As String In arr
If s1.Equals(str1) Then
b1 = True
Exit For
End If
Next
If b1.Equals(False) Then
Beep()
MessageBox.Show("Invalid code for this cell")
dgrModSubDetail.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = ""
End If
End If

At least with this kludge I don't have 50 lines of code to load the
arraylist. What is the best practice to perform this procedure? Is there
any method like

If s1 Not In {"C", "D", "F", ...}

Thanks,
Rich
 
G

Guest

At least with this kludge I don't have 50 lines of code to load the
arraylist. What is the best practice to perform this procedure? Is
there any method like

Use Regular Expressions. You can write your check using one line like:

"^[ABCDEFG]" which means not A or B or C ... Regular Expressions can check
everything from patterns, to lengths, to variations of strings. In anycase,
check the RegEx documentation for more details on the syntax.

Also, are you using the cell validating event to handle the check>
 
M

Mattias Sjögren

At least with this kludge I don't have 50 lines of code to load the
arraylist. What is the best practice to perform this procedure? Is there
any method like

If s1 Not In {"C", "D", "F", ...}

Arrays implement IList which has a Contains method, so you can call

If CType(arr, IList).Contains(s1) Then ...

You can also use the Array.IndexOf method.

If you're always checking single characters, you could store them all
in a single String and use the String.IndexOf method

Dim characters As String = "CDFINPRU"
....
If s1.Length = 1 AndAlso characters.IndexOf(s1, 0) = 0 Then ...


Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top