I want to add some numbers to a string in this code. But I don't know how can I do it without getting the following error:
System.InvalidCastException: 'Conversion from string "Happy Holidays!!! " to type 'Double' is not valid.' Internal Exception. FormatException: Input string was not in a correct format.
I don't want to SUM, I want to ADD. Here's the code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Day = Now.Day
Dim Month = Now.Month
Dim Year = Now.Year
Label1.Text = MonthName(Now.Month, True) //not necessary
If Now.Month = 12 Then
Me.Text = "Happy Holidays!!!" + " " + Day + "/" + Month + "/" + Year 'here's the problem
End If
End Sub
End Class
While the + operator can be used to concatenate Strings, it should not be used. The reason is because of situations like this where the compiler will attempt to treat the + as an addition operator instead of the String concatenation operator.
You have a couple of options:
Use the & operator
Use String interpolation
You can also simply call the ToString method on your DateTime object and pass in the desired format rather than getting the day, month, and year and passing them individually.
Take a look at this example:
Dim rightNow = DateTime.Now
Label1.Text = rightNow.ToString("MMMM")
If (rightNow.Month = 12) Then
Me.Text = $"Happy Holidays!!! {rightNow:d/M/yyyy}"
End If
Related
im doing a programming project and have been stumped on how to add more dates to the bolded dates
in a monthly calendar.
Private Sub BTN_Submit_Click(sender As Object, e As EventArgs) Handles BTN_Submit.Click
Dim format As String = "dd/MM/yyyy"
Dim boldeddates() As Date = FRM_EventsCalendar.MonthCalendar1.BoldedDates()
Dim dateTime As String = TXT_Date.Text
Dim dt As DateTime = Convert.ToDateTime(dateTime)
Dim str As String = dt.ToString(format)
Dim specialdate() As Date = {str}
**FRM_EventsCalendar.MonthCalendar1.BoldedDates = specialdate & boldeddates**
MsgBox("Date Added")
End Sub
i am trying to add them together so that instead of replacing the variables they both are bolded.
i have tried "&" and "," however none of these work. i was just wondering how this could be solved?
thx for any help :).
Use MonthCalendar.AddBoldedDate
FRM_EventsCalendar.MonthCalendar1.AddBoldedDate(specialdate)
I'm just getting back into coding to make a simple program to help with a project. I need to get html code into a string and I'm sure I'm doing something wrong but I'm just not sure what it is. Code is below...
Public Class Code_Generator
Dim r1 As String
Dim r2 As String
Dim r3 As String
Dim r4 As String
Dim Code As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Day.Text = r1
Week.Text = r2
Month.Text = r3
Weekend.Text = r4
Code = "<div id=""DL"">Day</div><div id=""DR"">$" + Day + "</div><br><div id=""DL"">Week</div><div id=""DR"">$" + Week + "</div><br><div id=""DL"">Month</div><div id=""DR"">$" + Month + "</div><br><div id=""DL"">Weekend</div> <div id=""DR"">$" + Weekend + "</div> <br>"
MessageBox.Show(Code)
End Sub
The operator (+) works for string concatenation, the same way the operator (&).
But the variables Day, Week, Month and Weekend refers to a TextBox (maybe another control), with the .Text property.
You are trying to concatenate the string "<div..." with the TextBox control itself. And there is no operator to do this.
You must concatenate the string with the .Text property of the TextBoxes:
Code = "<div..." & Day.Text & "..." & Week.Text ... and so on.
*I suggest you to use (&) for string concatenation, but it's totally a personal preference.
Using VB I am trying to create a name for the file by concatenating together the words "NewEmployeesOut" with the short date and time of the day. I am getting the following error System.NotSupportedException: 'The given path's format is not supported.' Below is the Code I am currently using, it seems like VB does not like a character I am using in my concat function when trying to export the .txt file.
Private Sub btnWrite_Click(sender As Object, e As EventArgs) Handles btnWrite.Click
Dim writeRecord As New StreamWriter
(New FileStream("NewEmployeesOut" & Date.Today.ToShortDateString & Date.Now.ToShortTimeString & ".txt", FileMode.Append, FileAccess.Write))
Dim EmployeeInformation1 As New EmployeeInformation()
writeRecord.Write(EmployeeInformation1.LastName & "|")
writeRecord.Write(EmployeeInformation1.FirstName & "|")
writeRecord.Write(EmployeeInformation1.DepartmentNo & "|")
writeRecord.Write(EmployeeInformation1.CreateUserName(EmployeeInformation1.FirstName, EmployeeInformation1.LastName) & "|")
writeRecord.WriteLine(EmployeeInformation1.CreatePassword)
writeRecord.Close()
End Sub
From MS docs https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file
The following characters are resevered.
< (less than)
> (greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
* (asterisk)
A file name formatted as follows will pass muster. The uppercase HH gives you 24 hour time.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim fileName As String = "NewEmployeesOut" & Now.ToString(" MMMM dd, yyyy HH,mm") & ".txt"
Debug.Print(fileName)
File.CreateText(fileName)
End Sub
In the immediate window...
NewEmployeesOut December 10, 2020 18,07.txt
Your short date probably looks like "31/12/2020" or "12/31/2020" which are no valid file names. Try something like
Dim now As DateTime = DateTime.Now
Dim fileName As String = $"NewEmployeesOut_{now:yyyy-MM-dd}_{now:HHmm}.txt"
Concerning the other question: It's the wrong place to post it, don't ask another question within a comment.
I think you have to learn a bit the basics first, read/watch some VB.Net tutorials and maybe some clean-code principles like the clean-code-techniques. Your questions suggest that you don't know yet how to write simple code.
Try to structure what you are doing, avoid (like in your example) to copy 4 times the same lines of code but to create functions instead to encapsulate business logic. e.g. writing a file has nothing to do with assembling a file name, therefore the two things should not be conducted in the same method etc.
But this all said, here an idea how you could structure your code (from the comment not the main question), although I'm not too positive about the usability of the two random digits...
Usage:
Dim fileName As String = GetFileName("Smith", "John")
Methods/Properties:
Private Shared Function GetFileName(lastName As String, firstName As String) As String
lastName = NormalizeAndCrop(lastName, 7)
firstName = NormalizeAndCrop(firstName, 10)
Dim randomNumber As Int32 = Randomizer.Next(0, 100)
Return $"{lastName}{firstName}{randomNumber:00}"
End Function
Private Shared Function NormalizeAndCrop(text As String, length As Int32)
'Check args
If (length < 0) Then Throw New ArgumentOutOfRangeException(NameOf(length), length, "A non-negative value expected!")
If (text Is Nothing) OrElse (length = 0) Then Return String.Empty
text = text.Normalize()
'Copy only valid characters
Dim result As New StringBuilder()
For i As Int32 = 0 To text.Length - 1
Dim c As Char = text(i)
If (IsValidFileNameChar(c)) Then
result.Append(c)
If (result.Length = length) Then
Return result.ToString()
End If
End If
Next
Return result.ToString()
End Function
Private Shared Function IsValidFileNameChar(c As Char) As Boolean
If (Char.IsControl(c)) Then Return False
If (InvalidFileNameChars.IndexOf(c) > -1) Then Return False
Return True
End Function
Private Shared ReadOnly Property Randomizer As Random = New Random(Environment.TickCount)
Private Shared ReadOnly Property InvalidFileNameChars As String = New String(Path.GetInvalidFileNameChars())
Say I have a textbox that has the following text : "hello" without the quotes. How would I take that text and output something like this : [Hh][Ee][Ll][Ll][Oo]
Is there a better/faster way than manually changing it?
Your question is more in a logic part.
Providing you have a textbox and a button that when you click the button, the output will pop in a message box... just use substring and convert each character to uppercase and lowercase and simply add the brackets like this
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim input As String = TextBox1.Text.Trim
Dim output As String = ""
For index As Integer = 0 To input.Length - 1
output += "[" + input.Substring(index, 1).ToUpper + "" + input.Substring(index, 1).ToLower + "]"
Next
MsgBox(output)
End Sub
End Class
from here below is the code added by Niranjan Kala. The code is not in vb but try to convert it.
//It would be better if you use StringBuilder rather than using SubString Method to create new strings in memory to append in output..See below code snippet:
string message ="hello"; // = TextBox1.Text.Trim()
StringBuilder br = new StringBuilder();
if(!string.IsNullOrEmpty(message))
{
char[] charArray = message.ToArray();
for(int index = 0;index< charArray.Length;index++)
{
br.AppendFormat("[{0}{1}]", Char.ToUpper(charArray[index]), Char.ToLower(charArray[index]));
}
}
string result = br.ToString();
result.Dump();
You can use something like this:
Function ReBuildStr(s As String) As String
Dim result As New System.Text.StringBuilder()
For Each c As Char In s
result.AppendFormat("[{0}{1}]", Char.ToUpper(c), Char.ToLower(c))
Next
Return result.ToString()
End Function
Or if you don't want to use StringBuilder you can use a String using this inside the For:
result &= "[" & Char.ToUpper(c) & Char.ToLower(c) & "]"
If Textbox1.text contains a string value of ZU4, how can I convert that string to it's numeric ASCII codes, and output it to a second text box?
I'd like to do this using a FOR LOOP conditional statement which will read every character in INPUT?
Sample:
INPUT Textbox1.Text = ZU4
OUTPUT Textbox2.Text = 908552
You could also use LINQ:
TextBox2.Text = String.Join(String.Empty, From c In Textbox1.Text.ToCharArray Select (Asc(c).ToString))
Could be useful on some job interviews... :)
All of the other answers will work with your given example, however, some of the suggestions are using unicode encoding rather than ASCII. If strictly adhering to ASCII encoding is important, then you should explicitly specify the encoding that you want to use.
Convert.ToInt32 uses UTF-16 encoding. I'm not sure what CInt will do, but I suspect it works the same way. Using Asc is better, but it is still dependent on the code page setting for the thread, so it's still not entirely safe. Besides that, Asc is an old VB6 function which is provided in VB.NET, primarily for backwards compatibility.
Therefore, I would recommend using the ASCIIEncoding class instead. You can get an instance of that class using the shared ASCII property of the Encoding class in the System.Text namespace, for instance:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
For Each b As Byte In Encoding.ASCII.GetBytes(text)
builder.Append(b.ToString())
Next
Return builder.ToString()
End Function
Then, you can call the function like this:
Textbox2.Text = ConvertTextToAsciiDigits(Textbox1.Text)
However, I can't imagine that the resulting string will be usable unless every character results in a two digit number. Therefore, I would force it to be two digits by doing something like this:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
For Each b As Byte In Encoding.ASCII.GetBytes(text)
If b > 99 then
Throw New FormatException() ' Throws an exception if the value is three digits
End If
builder.Append(b.ToString("00")) ' Adds a leading zero to one-digit values
Next
Return builder.ToString()
End Function
To add a hyphen after every fourth digit, as you mentioned in a comment below, you could just keep track of the total digits added since the last hyphen, like this:
Public Function ConvertTextToAsciiDigits(text As String) As String
Dim builder As New StringBuilder()
Dim digitsSinceHyphen As Integer = 0
For Each b As Byte In Encoding.ASCII.GetBytes(text)
If b > 99 then
Throw New FormatException()
End If
builder.Append(b.ToString("00"))
digitsSinceHyphen += 2
If digitsSinceHyphen >= 4 Then
builder.Append("-")
digitsSinceHyphen = 0
End If
Next
Return builder.ToString()
End Function
Here is one approach, in C#:
Textbox2.Text = string.Empty;
foreach(var c in Textbox1.Text)
{
Textbox2.Text += ((int)c).ToString();
}
VB.NET:
Textbox2.Text = String.Empty
For Each c As Char In Textbox1.Text
Textbox2.Text = Textbox2.Text + Convert.ToInt32(c).ToString()
Next
It:
Clears out Textbox2.Text
Loops over each character in the input
Concatenates the integer value output as a string to the output text
TextBox2.Text = ""
For i As Integer = 0 To TextBox1.TextLength - 1
TextBox2.Text += Asc(TextBox1.Text(i)).ToString()
Next
i modified the code from this Link
Function AsciiEncode(ByVal value As String) As String
Dim encValue As New System.Text.StringBuilder(value.Length * 6)
Dim c As Char
For Each c In value
encValue.Append(Convert.ToInt32(c))
Next
Return encValue.ToString()
End Function
usage:
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
TextBox2.Text = AsciiEncode(TextBox1.Text)
End Sub