VB.net/C# Datatable.Select with special characters (brackets) - vb.net

I have a vb.net Project with a Dataset with some Cells with Strings like "JB-Y[ST]Y". My Problem is you can't use datatable.select("Column like 'JB-Y[ST]Y'") because of the brackets (the select thinks this is a pattern, but I need an exact match). Anyone has an idea on this topic? I can't find a solution... Thank you!

I can't find a solution using Regex.Replace so I have a brute force solution like this
Public Function ReplaceBrackets(search as String) As String
Dim sb As StringBuilder = New StringBuilder()
For Each c In search
If c = "[" Then
sb.Append("[[]")
Else if c = "]" Then
sb.Append("[]]")
Else
sb.Append(c)
End If
Next
return sb.ToString()
End Function
And you can call it in your Select statement like this
datatable.Select("Column like '" & ReplaceBrackets(search) & "'")

Related

My List(OF Strings) are being saved as system.string (Empty)

I'm trying to delete a selected row, then save the rest into a file. However, when I save it, it totally empties the file.
Console.Write("Please eneter the first name of the student you wish to search for: ")
searchfname = Console.ReadLine
searchfname = StrConv(searchfname, VbStrConv.ProperCase)
Console.Write("Please enter the second name of the student you wish to search for: ")
searchsname = Console.ReadLine
searchsname = StrConv(searchsname, VbStrConv.ProperCase)
Dim foundItem() As String = Nothing
Dim foundline As String = Nothing
Dim fnsearch As String = String.Join(searchfname, searchsname)
Dim lines As New List(Of String)(File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv"))
For Each line As String In lines
If searchfname = item(3) And searchsname = item(4) Then
Console.WriteLine(line)
Console.WriteLine()
Console.WriteLine("Are you sure you wish to delete this record? (y/n)")
End If
Dim answer As String
answer = Console.ReadLine
If answer = "y" Or answer = "Y" Then
Console.Clear()
lines.Remove(line)
Using sw As New StreamWriter("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
sw.WriteLine(lines.ToString)
End Using
ElseIf answer = "n" Or answer = "N" Then
staffmenu()
End If
Next
Look at this line in your code:
sw.WriteLine(lines.ToString)
Extract the lines.ToString expression from that statement. The result of that expression is "System.String". You are telling your stream writer to write the text "System.String" to the file.
To fix it, you need something more like this:
Using sw As New StreamWriter("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
For Each line As String In lines
sw.WriteLine(line)
Next line
End Using
The method List(Of T).ToString does not produce a value that includes the elements of the collection. Instead it will just return the type name.
The API you are looking for is File.WriteAllLines. Using this instead of StreamWriter and the Using block
File.WriteAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv", lines)
I can see that this issue can be resolved from the given answers and comment, but I would like to add an alternative to use Join function in writing to a file. Try like this may be of help:
Using sw As New StreamWriter(.....)
sw.WriteLine(Join(lines.ToArray(), Environment.NewLine))
End Using
Since using VB.Net, this is a vb.net specific solution can not be used in C#. For C#, use string.join instead.
Hope it helps too!

Lowercase the first word

Does anybody know how to lowercase the first word for each line in a textbox?
Not the first letter, the first word.
I tried like this but it doesn't work:
For Each iz As String In txtCode.Text.Substring(0, txtCode.Text.IndexOf(" "))
iz = LCase(iz)
Next
When you call Substring, it is making a copy of that portion of the string and returning it as a new string object. So, even if you were successfully changing the value of that returned sub-string, it still would not change the original string in the Text property.
However, strings in .NET are immutable reference-types, so when you set iz = ... all you are doing is re-assigning the iz variable to point to yet another new string object. When you set iz, you aren't even touching the value of that copied sub-string to which it previously pointed.
In order to change the value of the text box, you must actually assign a new string value to its Text property, like this:
txtCode.Text = "the new value"
Since that is the case, I would recommend building a new string, using a StringBuilder object, and then, once the modified string is complete, then set the text box's Text property to that new string, for instance:
Dim builder As New StringBuilder()
For Each line As String In txtCode.Text.Split({Environment.NewLine}, StringSplitOptions.None)
' Fix case and append line to builder
Next
txtCode.Text = builder.ToString()
The solutions here are interesting but they are ignoring a fundamental tool of .NET: regular expressions. The solution can be written in one expression:
Dim result = Regex.Replace(txtCode.Text, "^\w+",
Function (match) match.Value.ToLower(), RegexOptions.Multiline)
(This requires the import System.Text.RegularExpressions.)
This solution is likely more efficient than all the other solutions here (It’s definitely more efficient than most), and it’s less code, thus less chance of a bug and easier to understand and to maintain.
The problem with your code is that you are running the loop only on each character of the first word in the whole TextBox text.
This code is looping over each line and takes the first word:
For Each line As String In txtCode.Text.Split(Environment.NewLine)
line = line.Trim().ToLower()
If line.IndexOf(" ") > 0 Then
line = line.Substring(0, line.IndexOf(" ")).Trim()
End If
// do something with 'line' here
Next
Loop through each of the lines of the textbox, splitting all of the words in the line, making sure to .ToLower() the first word:
Dim strResults As String = String.Empty
For Each strLine As String In IO.File.ReadAllText("C:\Test\StackFlow.txt").Split(ControlChars.NewLine)
Dim lstWords As List(Of String) = strLine.Split(" ").ToList()
If Not lstWords Is Nothing Then
strResults += lstWords(0).ToLower()
If lstWords.Count > 1 Then
For intCursor As Integer = 1 To (lstWords.Count - 1)
strResults += " " & lstWords(intCursor)
Next
End If
End If
Next
I used your ideas guys and i made it up to it like this:
For Each line As String In txtCode.Text.Split(Environment.NewLine)
Dim abc() As String = line.Split(" ")
txtCode.Text = txtCode.Text.Replace(abc(0), LCase(abc(0)))
Next
It works like this. Thank you all.

Find space in string, remove everything after it

Hoping this would be simple, but doesnt seem to be.
I've got a variable in vb.net 'contactname'.
format is like "John Smith"
I want to get just the forename from this, but cant seem to do it.
I've found and adapted some examples from google, but nothing seems to work :(
Just Split the string on spaces and take the first element:
contactname.Split(" "c)(0)
Could use Regex if you like:
Public Shared Function RegexGetForename(ByVal str As String) As String
Dim a = New System.Text.RegularExpressions.Regex("^(\w+)")
If a.IsMatch(str) Then
Return a.Match(str).Value
Else
Return vbNull
End If
End Function
Dim forename as string
Dim i = contactname.IndexOf(" ")
If i <> -1 Then
forename = contactname.Substring(0, i)
MsgBox(forename)
End If
try it

How to get rid of the zero '0' numeric from a string?

BEFORE:
Johnson0, Yvonne
AFTER:
Johnson, Yvonne
String functions for Access can be found at http://www.techonthenet.com/access/functions/string/replace.php
In your example, code like
Replace("Johnson0", "0", "")
will do the trick for the particular string Johnson0. If you need to only remove the zero if it is the last character, play with the additional start and count parameters described in the link above.
You can try executing following query..
UPDATE table set
columnName = REPLACE(columnName,'0','')
WHERE columnName LIKE "%0%";
This will replace all occurrence of "0" with "".
The answer you submitted clarifies your requirement. Based on that, you don't need to create a user-defined function if your Access version is 2000 or later. You can get the same result with the Replace() function.
MsgBox Replace("Jonson0, Yvonne", "0,", ",")
One approach is to create a custom function
See http://www.techonthenet.com/access/functions/misc/alphanumeric.php for an example. You could do something similar, but in the loop you would only keep the alpha characters.
Public Sub xxx()
MsgBox RemoveStr0("Jonson0, Yvonne")
End Sub
Public Function RemoveStr0(sString As String) As String
Dim ipos As Long, sTemp As String
ipos = InStr(1, sString, "0,")
sTemp = Mid$(sString, 1, ipos - 1)
sTemp = sTemp & Mid$(sString, ipos + 1)
RemoveStr0 = sTemp
End Function
if you can pull it out to java or another OO lang you can just do a matching using regexes.

String Concatenation in VBA

I've got this function:
Function GetFullNameCSV() As String
GetFullNameCSV = Replace(ThisWorkbook.FullName, ".xlsm", ".txt")
End Function
If the code looked like this hard coded:
Filename:= "C:\directory\filename.txt"
I could just replace it with this and get the same result:
Filename:= GetFullNameCSV()
Problem is it appears in the case of this string:
Connection:= "TEXT;C:\directory\filename.txt"
I need to use string concatenation, guessing something like this:
Connection:= "\"TEXT;+GetFullNameCSV()+\""
What the code I need to use? Thanks.
Assuming that all the sections are always delimited with a ;, just split the string into it's parts and then do your changes and then join it together again.
So with your sample I think it would be something like (please note, written from memory, so might not be completely correct):
Dim parts() as String
parts = Split(str, ";")
parts(2) = GetFullNameCSV() ' assuming that part 2 is the one you want to replace
str = Join(parts, ";")