How to skip DateTime conversion? - vb.net

in VB.NET I have TextBox with masked time input such as
__:__
Before I save this to SQL database I have a conversion to iso format like:
Dim MyTime As DateTime = DateTime.ParseExact(txtMyTime.Text, "HH:mm", Nothing)
Dim isoMyTime As String = MyTime.ToString("HH:mm:ss")
Now my question is how to write to database Null value if this text box is empty without time value input?

not sure if you are stuck on SQL, or to figure out wether the textbox has been given a value.
when you write to database, you define the columns that you want to write to:
insert into Table1(Forename, Surname)
values(John, Jehnson)
if you want the surname to be null, simply do not mention it:
insert into Table1(Forename)
values(John)
Make sure your column is designed to allow nulls.
to figure out if the textbox has a value, simply Check if the values matches a actual valid format
solution 1
you can achieve this with a Regex:
[0-9]{2}:[0-9]{2}
this regex makes sure that there are 2 numbers before and after the : sign.
solution 2
You can also replace the textbox with 2 numericupdown controls.
solution 3
another option is to try to parse it manually.
dim ISvalid as boolean = true
if textbox1.contains(":")
if split(textbox1, ":").count = 2
if split(textbox1, ":").first.length = 2 andalso split(textbox1, ":").last.length = 2
if IsNumeric(split(textbox1, ":").first) andalso isnumeric(split(textbox1, ":").last
' this is a valid value
else
isvalid = false
end if
else
isvalid = false
end if
else
isvalid = false
end if
else
isvalid = false
end if
if isvalid then
Dim MyTime As DateTime = DateTime.ParseExact(txtMyTime.Text, "HH:mm", Nothing)
Dim isoMyTime As String = MyTime.ToString("HH:mm:ss")
end if

Related

Gridview CustomUnboundColumnData Date column with custom strings filter error

I have a column with dates and strings in my table (varchar) named DateColumn and i want to show it as dates to be able to filter by date. I first tried to create an unbound column with unboundexpression with GetData(DateColumn) and it worked, all the strings with dates where converted to date and the other was #Err. And i was able to filter by date. but i wanted to control these #Err: its empty? its "otherstring"? or its something other?
so i tried with CustomUnboundColumnData function:
Try
value = Date.Parse(view.GetListSourceRowCellValue(listSourceRowIndex, columna))
Catch ex As Exception
If IsDBNull(view.GetListSourceRowCellValue(listSourceRowIndex, columna)) Then
value = DBNull.Value
Else
If view.GetListSourceRowCellValue(listSourceRowIndex, columna) = "" Then
value = DBNull.Value
ElseIf view.GetListSourceRowCellValue(listSourceRowIndex, columna) = "otherstring" Then
value = "#otherstring"
Else
value = "#Err"
End If
End If
End Try
but now when I try to filter by value (by date) i get an error:
Cannot compare two items in array.:
System.ArgumentException: The object must be of type String.
if I replace the "#Err" and "#otherstring" for DBNull.Value it works again. but i need to be able to put other strings.
Don't use the Try...End Try for fully expected errors. You are not using ex at all.
Use a TryParse. You can distinguish the nulls and other strings by assigning an obviously bogus date. Create a list of the bad strings for review.
Dim d As Date
Dim value As Date
Dim errList As New List(Of String)
If Date.TryParse(View.GetListSourceRowCellValue(listSourceRowIndex, columna), d) Then
value = d
ElseIf IsDBNull(View.GetListSourceRowCellValue(listSourceRowIndex, columna)) Then
value = CDate("January 2, 0001 ")
ElseIf View.GetListSourceRowCellValue(listSourceRowIndex, columna) = "" Then
value = CDate("January 2, 0001 ")
Else
value = CDate("January 1, 0001")
errList.Add(View.GetListSourceRowCellValue(listSourceRowIndex, columna).ToString)
End If

retrive empty or null value of date from datagridview ? VB Net

Dim datagrid1 As Date = Nothing
Dim remaning1 As DateTime = DateTime.Now
Dim answer1 As Integer = Nothing
datagrid1 = DataGridView2.Rows(0).Cells(4).Value
if datagridview value is empty then there is an error. How to rectify this issue.
Do a check whether the value is null and set the value accordingly:
If Not IsDBNull(DataGridView2.Rows(0).Cells(4).Value) Then
datagrid1.Value = DataGridView2.Rows(0).Cells(4).Value
End If
The question is a bit unclear... but I think you want to check that the value in the DataGridView is a valid date... If so, use the below
If TypeOf(DataGridView2.Rows(0).Cells(4).Value) Is Date Then
'Logic here...
End If

Visual basic palindrome code

I am trying to create an application which will determine whether a string entered by user is a palindrome or not.
Is it possible to do without StrReverse, possibly with for next loop. That's what i have done so far.
Working one, with StrReverse:
Dim userInput As String = Me.txtbx1.Text.Trim.Replace(" ", "")
Dim toBeComparedWith As String = StrReverse(userInput)
Select Case String.Compare(userInput, toBeComparedWith, True)
Case 0
Me.lbl2.Text = "The following string is a palindrom"
Case Else
Me.lbl2.Text = "The following string is not a palindrom"
End Select
Not working one:
Dim input As String = TextBox1.Text.Trim.Replace(" ", "")
Dim pallindromeChecker As String = input
Dim output As String
For counter As Integer = input To pallindromeChecker Step -1
output = pallindromeChecker
Next counter
output = pallindromeChecker
If output = input Then
Me.Label1.Text = "output"
Else
Me.Label1.Text = "hi"
End If
While using string reversal works, it is suboptimal because you're iterating over the string at least 2 full times (as string reversal creates a copy of a string because strings are immutable in .NET) (plus extra iterations for your Trim and Replace calls).
However consider the essential properties of a palindrome: the first half of a string is equal to the second half of the string in reverse.
The optimal algorithm for checking a palindrome needs only iterate through half of the input string - by comparing value[n] with value[length-n] for n = 0 to length/2.
In VB.NET:
Public Shared Function IsPalindrome(value As String) As Boolean
' Input validation.
If value Is Nothing Then Throw New ArgumentNullException("value")
value = value.Replace(" ", "") // Note String.Replace(String,String) runs in O(n) time and if replacement is necessary then O(n) space.
' Shortcut case if the input string is empty.
If value.Length = 0 Then Return False ' or True, depends on your preference
' Only need to iterate until half of the string length.
' Note that integer division results in a truncated value, e.g. (5 / 2 = 2)...
'... so this ignores the middle character if the string is an odd-number of characters long.
Dim max As Integer = value.Length - 1
For i As Integer = 0 To value.Length / 2
If value(i) <> value(max-i) Then
' Shortcut: we can abort on the first mismatched character we encounter, no need to check further.
Return False
End If
Next i
' All "opposite" characters are equal, so return True.
Return True
End Function

My function on VBA does give some false negative output

Recently, I wrote a code in order to check the Social Insurance Number issued in Germany.
I have 3 outputs: surname, dob and the given Social Insurance Number. Between 3rd and 8th digits it consists of date month and last two years of birth.
However, in some cases, it does return false negative. Can anyone suggest any improvements? I am very new to VBA and coding in general, that's why feel free to check and suggest any improvements.
I will post my code, an example where it gives true positive and examples where it does give false negatives.
__Steinbach 01.12.1991 12011291S533
false negative results for
Akyol 31.10.1993 13311093A017__
Voormann 22.11.1995 53221195V018__
Köhler 15.10.1997 14151097K056__
Xheladini 22.10.1991 65221091X509__
The function in Visual Basic
Public Function firstDigitsSocIn(surname As String, dob As Date, socialSecurityNumber As String) As String
'defining variables (add gender after surname when data is available)
Dim dayOfMonth As Integer
Dim monthSoc As Integer
Dim yearSoc As Integer
Dim firstCharSurname As String
Dim customMadeNumber As String
'Dim genderCode As Integer enable when having genders in data set
'Dim genderCheck As Boolean
Dim resultFirst7Chars As Boolean
Dim resultInclGenderCheck As Boolean
Dim resultFinal As Boolean
'setting up variables with correct values
dayOfMonth = Day(dob)
monthSoc = Month(dob)
yearSoc = Right(Year(dob), 2)
firstCharSurname = Left(surname, 1)
'genderCode = Left(Right(socialSecurityNumber, 3), 2)
'if gender = "M" am
'custommadenumber is composed using the credentials of the user
customMadeNumber = dayOfMonth & monthSoc & yearSoc & firstCharSurname
resultFirst7Chars = StrComp(Mid(socialSecurityNumber, 3, 7), customMadeNumber, vbBinaryCompare)
'If gender = "M" And genderCode < 50 Then
'genderCheck = True
'ElseIf gender = "F" And genderCode > 50 Then
'genderCheck = True
'Else
'genderCheck = False
'End If
'resultInclGenderCheck = resultFirst7Chars And genderCheck
'resultFinal = resultInclGenderCheck And True 'put Pruefziffer check here as well
firstDigitsSocIn = resultFirst7Chars
End Function
I think you have two severe problems.
You build your custom number with Integers instead of strings. That means that numbers less that 10 will lose their leading 0.
You use StrComp when you actually only want to check if strings are equal. That wouldn't be too bad but you are casting the result as Boolean (because resultFirst7Chars is a boolean). StrComp returns 0 if the strings are equal and -1 or +1 otherwise. But when you case 0, -1 and 1 as booleans you get False, True, and True, the exact opposite of what you want!
Prakash alreadygave a solution to the second problem. Another would be to just use
resultFirst7Chars = (socialSecurityNumber = customMadeNumber)
Edit: Since Prakash deleted his answer here is what he suggested:
resultFirst7Chars = (StrComp(Mid(socialSecurityNumber, 3, 7), customMadeNumber, vbBinaryCompare) = 0)
i.e. checking if StrComp returned 0 or not.
For the first problem, you could use dayOfMonth = Format(Day(dob), "00") to get leading zeros (Declare dayOfMonth and the others as strings or you will lose them again!)
Dim dayOfMonth As String
'...
Dim yearSoc As String
dayOfMonth = Format(Day(dob), "00")
'...
yearSoc = Right(CStr(Year(dob))) 'CStr wouldn't be necessary but this way it's more obvious what is happening.
Finally, your function should probably return a boolean instead of a string.

vb.net string contains only 4 digit numbers(or a year)

how can i check if a string only contains 4 digit numbers ( or a year )
i tried this
Dim rgx As New Regex("^/d{4}")
Dim number As String = "0000"
Console.WriteLine(rgx.IsMatch(number)) // true
number = "000a"
Console.WriteLine(rgx.IsMatch(number)) // false
number = "000"
Console.WriteLine(rgx.IsMatch(number)) //false
number = "00000"
Console.WriteLine(rgx.IsMatch(number)) // true <<< :(
this returns false when its less than 4 or at characters but not at more than 4
thanks!
I actually wouldn't use a regex for this. The expression is deceptively simple (^\d{4}$), until you realize that you also need to evaluate that numeric value to determine a valid year range... unless you want years like 0013 or 9015. You're most likely going to want the value as an integer in the end, anyway. Given that, the best validation is probably just to actually try to convert it to an integer right off the bat:
Dim numbers() As String = {"0000", "000a", "000", "00000"}
For Each number As String In numbers
Dim n As Integer
If Integer.TryParse(number, n) AndAlso number.Length = 4 Then
'It's a number. Now look at other criteria
End If
Next
Use LINQ to check if All characters IsDigit:
Dim result As Boolean = ((Not number Is Nothing) AndAlso ((number.Length = 4) AndAlso number.All(Function(c) Char.IsDigit(c))))
You should use the .NET string manipulation functions.
Firstly the requirements, the string must:
Contain exactly four characters, no more, no less;
Must consist of a numeric value
However your aim is to validate a Date:
Function isKnownGoodDate(ByVal input As String) As Boolean 'Define the function and its return value.
Try 'Try..Catch statement (error handling). Means an input with a space (for example ` ` won't cause a crash)
If (IsNumeric(input)) Then 'Checks if the input is a number
If (input.Length = 4) Then
Dim MyDate As String = "#01/01/" + input + "#"
If (IsDate(MyDate)) Then
Return True
End If
End If
End If
Catch
Return False
End Try
End Function
You may experience a warning:
Function isKnownGoodDate does not return a value on all code
paths. Are you missing a Return statement?
this can be safely ignored.