How to get text and a variable in a messagebox - vb.net

I just need to know how to have plain text and a variable in a messagebox.
For example:
I can do this: MsgBox(variable)
And I can do this: MsgBox("Variable = ")
But I can't do this: MsgBox("Variable = " + variable)

As has been suggested, using the string.format method is nice and simple and very readable.
In vb.net the " + " is used for addition and the " & " is used for string concatenation.
In your example:
MsgBox("Variable = " + variable)
becomes:
MsgBox("Variable = " & variable)
I may have been a bit quick answering this as it appears these operators can both be used for concatenation, but recommended use is the "&", source http://msdn.microsoft.com/en-us/library/te2585xw(v=VS.100).aspx
maybe call
variable.ToString()
update:
Use string interpolation (vs2015 onwards I believe):
MsgBox($"Variable = {variable}")

Why not use:
Dim msg as String = String.Format("Variable = {0}", variable)
More info on String.Format

I kind of run into the same issue. I wanted my message box to display the message and the vendorcontractexpiration. This is what I did:
Dim ab As String
Dim cd As String
ab = "THE CONTRACT FOR THIS VENDOR WILL EXPIRE ON "
cd = VendorContractExpiration
If InvoiceDate >= VendorContractExpiration - 120 And InvoiceDate < VendorContractExpiration Then
MsgBox [ab] & [cd], vbCritical, "WARNING"
End If

MsgBox("Variable {0} " , variable)

I wanto to display the count of rows in the excel sheet after the filter option has been applied.
So I declared the count of last rows as a variable that can be added to the Msgbox
Sub lastrowcall()
Dim hm As Worksheet
Dim dm As Worksheet
Set dm = ActiveWorkbook.Sheets("datecopy")
Set hm = ActiveWorkbook.Sheets("Home")
Dim lngStart As String, lngEnd As String
lngStart = hm.Range("E23").Value
lngEnd = hm.Range("E25").Value
Dim last_row As String
last_row = dm.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox ("Number of test results between the selected dates " + lngStart + "
and " + lngEnd + " are " + last_row + ". Please Select Yes to continue
Analysis")
End Sub

Related

Split text in all lines inside of a string

Originally the Keywords will we pulled out from a text file located on a web server.
Dim KeyWords As String = Split(Split(TempSMTPFile, "# Keywords #")(1), "# Keywords #")(0)
I want to create a function that will split out all the keywords inside a string
The keywords in this example will be:
' This list might be changed to more or less keywords.
Dim KeyWords As String = "[One=Test1]" & vbNewLine & "[Two=Test2]" & vbNewLine & "[Three=Test3]"
' I Need a function to split out all keywords and do below check between all splits.
If KeyWords.ToLower.Contains("[" & Splited_keyword & "=") Then ' One, Two, Three
MsgBox(Split(Split(KeyWords, "[" & Splited_keyword & "=")(1), "]")(0)) ' Test1, Test2, Test3
End If
' This should print OneTest1, TwoTest2, ThreeTest3
Thanks for your comments, I was able to solve this with this solution.
Dim str As String() = keywords.Split(New [Char]() {CChar(vbCrLf)})
For Each s As String In str
If s.Contains("[") Then
Dim SplittedKeyword = Split(Split(s, "[")(1), "=")(0)
If TextUserShortDescription.Text.ToLower.Contains(SplittedKeyword.ToLower) Then
MsgBox(SplittedKeyword & (Split(Split(s, "[" & SplittedKeyword & "=")(1), "]")(0)))
End If
End If
Next
This could help you (untested):
Dim keyValues as String()
keyValues = KeyWords.Split(Environment.NewLine)
For Each (keyvalue as string in keyValues)
MsgBox(keyvalue.SubString(1, keyvalue.IndexOf("["c) + " " + keyvalue.SubString(keyvalue.IndexOf("="c), keyvalue.LastIndexOf("]"c)
End For

VB.net string join, adds unneeded space

Having some issues in vb.net string to join two strings together for output to a txt document. My text document is getting an extra space between the two strings I join. This should not be happening.
If System.IO.File.Exists(path) = True Then
' Create a file to write to.
Dim sw As StreamWriter = System.IO.File.CreateText(path)
sw.WriteLine("Attribute VB_Name = " & Chr(34) & "KbTest" & Chr(34))
sw.WriteLine("")
sw.WriteLine("Public Sub DoKbTest()")
sw.WriteLine("'code here")
sw.WriteLine("Dim catia")
sw.WriteLine("set catia = GetObject(, " & Chr(34) & "CATIA.Application" & Chr(34) & ")")
sw.WriteLine("Dim partDocument1")
sw.WriteLine("Set partDocument1 = catia.ActiveDocument")
sw.WriteLine("Dim part1")
sw.WriteLine("Set part1 = partDocument1.Part")
sw.WriteLine("Dim hybridShapeFactory1")
sw.WriteLine("Set hybridShapeFactory1 = part1.HybridShapeFactory")
sw.WriteLine("Dim hybridShapeDirection1")
sw.WriteLine("Set hybridShapeDirection1 = hybridShapeFactory1.AddNewDirectionByCoord(1#, 2#, 3#)")
sw.WriteLine("Dim hybridBodies1")
sw.WriteLine("Set hybridBodies1 = part1.HybridBodies")
sw.WriteLine("Dim hybridBody1")
sw.WriteLine("Set hybridBody1 = hybridBodies1.Item(" & Chr(34) & "PointSetx" & Chr(34) & ")")
sw.WriteLine("dim skteches1")
sw.WriteLine("Set sketches1 = hybridBody1.HybridSketches")
sw.WriteLine("Dim sketch1")
sw.WriteLine("Set sketch1 = sketches1.Item(" & Chr(34) & "Sketch.1" & Chr(34) & ")")
sw.WriteLine("Dim reference1")
sw.WriteLine("Set reference1 = part1.CreateReferenceFromObject(sketch1)")
sw.WriteLine("Dim hybridShapeExtremum1")
sw.WriteLine("Set hybridShapeExtremum1 = hybridShapeFactory1.AddNewExtremum(reference1, hybridShapeDirection1, 1)")
sw.WriteLine("hybridBody1.AppendHybridShape hybridShapeExtremum1")
sw.WriteLine("Dim reference2")
Dim lessOneCount As String
Dim spacing As Double = 0
Dim count As String
Dim setString As String
'loop
THIS IS THE PART OF THE CODE THAT IS ADDING EXTRA SPACES
For i = 1 To numbOfPoints Step 1
count = Str(i)
count.Replace(" ", "")
MsgBox(count)
If i < 2 Then
lessOneCount = "hybridShapeExtremum1"
Else
lessOneCount = "HybridShapePointOnCurve" + Str(i - 1)
End If
sw.WriteLine("reference2 = part1.CreateReferenceFromObject(" + lessOneCount + ")")
setString = "Dim hybridShapePointOnCurve" + count
sw.WriteLine(setString)
setString = "hybridShapePointOnCurve" + count + " = hybridShapeFactory1.AddNewPointOnCurveWithReferenceFromDistance(reference1, reference2, spacing, False)"
sw.WriteLine(setString)
setString = "hybridShapePointOnCurve" + count + ".DistanceType = 1"
sw.WriteLine(setString)
setString = "hybridBody1.AppendHybridShape(hybridShapePointOnCurve" + count + ")"
sw.WriteLine(setString)
Next
sw.WriteLine("End Sub")
sw.Flush()
sw.Close()
End If
Sample output:
Dim hybridShapePointOnCurve 2
SHOULD be:
Dim hybridShapePointOnCurve2
What modifications should I make to the way I join strings?
Thanks!
Realized my comment didn't answer your question completely, so a few things:
The String.Replace method doesn't work like you think it does. Saying count.Replace(" ", "") doesn't actually change the variable count; the function actually returns a new string. For it work like you want, you would need to do count = count.Replace(" ", "").
Consider using a StringBuilder instead of concatenating a bunch of strings together. It will greatly improve performance. When using the StringBuilder class, you also wouldn't need to write to the StreamWriter until the very end, simply by calling sw.Write(stringBuilderObject.ToString())
I haven't used VB.NET in a while, but I would check what Str(i) returns. Instead of using VB functions, consider using .NET functions by saying count = i.ToString(). According to Sky, the Str function indeed returns a space because it reserves it for the negative sign. Based on this, I would use the .ToString() method instead.
I spoke to quickly in my comment, the Str function reserves room for the sign, since it is a positive number there is no sign, if it was negative there would be a minus sign there. Try Trim(Str(i)) instead
From above link(emphasis mine):
This example uses the Str function to return a String representation of a number. When a positive number is converted to a string, a leading space is always reserved for its sign.

Get value of a string that is passed as parameter

I need to pass in parameters to my sub/function.
When the parameter is passed, the value in the string, I would like to get the value evaluated and sent as:
Dim strParams As String = drRow(0)
' drRow is a row from DB Table. the value in drRow(0) =
' "#FromDate=""" & Now.AddDays(-10).ToShortDateString & """&#ToDate=""" & Now.AddDays(-4).ToShortDateString "
I would like to see this converted to:
Dim strFinal as string
strFinal = ProcessString(strParams)
End Result should be:
strFinal = "#FromDate=10/09/2011&#ToDate=10/15/2011"
Any ideas how I can do this. I am getting the initial string from DB, I need to convert to the final string, I am not able to figure out how to write the "ProcessString" function.
Thanks for looking.
"IF" you can change your parameter statement to something simple like:
#FromDate=;-10;#ToDate=;-4
Then you can do something like this:
Dim strParams As String = "#FromDate=;-10;#ToDate=;-4"
Dim value As String = String.Empty
Dim parts() As String = strParams.Split(";"c)
If parts.Length = 4 Then
Dim fromDays As Integer
Dim toDays As Integer
If Integer.TryParse(parts(1), fromDays) AndAlso Integer.TryParse(parts(3), toDays) Then
value = parts(0) + Now.AddDays(fromDays).ToShortDateString + parts(2) + Now.AddDays(toDays).ToShortDateString
End If
End If
MessageBox.Show("Value = " & value)
If it's anything more complicated than that then you will have to start parsing every part of your string with lots of If and Select statements-- you should probably heed Jim Mischel's advice and try a different approach.
This is the end result of what i used based on suggestions.. Thanks Guys.
Public Function ProcessParameters(ByVal strParams As String) As String
Dim arrParams() As String
'strParams = "#FromDate=-10;&#ToDate=-4;&#CompanyID=1"
arrParams = strParams.Split(";")
Dim arrP() As String
Dim strFinalParams As String = ""
For Each strP As String In arrParams
arrP = strP.Split("=")
If arrP(0).ToString.EndsWith("Date") Then
strFinalParams &= arrP(0) & "=" & Now.AddDays(arrP(1)).ToShortDateString
Else
strFinalParams &= arrP(0) & "=" & arrP(1)
End If
Next
Return strFinalParams
End Function
}

for loop for a string variable

this is my code -
for i as integer = 0 to rows.count - 1
output &= "Name =" & row(i)("Name")
output &= "lastName =" & row(i)("lastName")
... 50 more fields
next
i need the output to be like this
Applicant1Name = MikeApplicant1lastName = ditkaApplicant2Name = TomApplicant2lastName = Brady ...
how do i do this without putting the following code 50 times -
output &= "Applicant" & i.tostring() + 1 &"Name =" & row(i)("Name")
... and so on.
is there a way to make a for loop and run applicant 1,2,3,4.... in one shot?
thanks
Try:
Dim output as New StringBuilder("")
For i as Integer = 0 To rows.Count - 1
output.append("Applicant" + i.ToString())
Foreach(col as DataColumn in dt.Columns) ' The datatable where your rows are
Dim colName as string = col.ColumnName
output.append(colName & "=" & rows(i)(colName).ToString())
Next
If i < rows.Count - 1 Then output.Append("|")
Next
StringBuilder is faster for string concatenations, and if you keep your rows in a datatable (which I assume is happening because that's how it looks like you're accessing them), then you can just iterate through the columnnames at the top level.
You really cant as you are trying to append 50 different fields.
The only thing you can shorten is the variable name:
Dim strLN as String = row(i)("lastName")
Dim strFirstName as String = row(i)("firstName")
Then you simply put it all together
output &= strLN & strFirstName...etc
looks like you want to create an array of all the fields you have and then include a nested loop.
Dim fields As String() = {"Name", "LastName", "SSN", "Birthdate"}
Dim output As String = ""
For i As Integer = 1 To rows.count
For Each field As String In fields
output = String.Concat(output, "Applicant ", i, field, "=", row(i)(field), " ")
Next
Next

Looping through a request.querystring in VB.NET

I am trying to loop through a query string and pull out certain values as in:
?ProductID=1234&ProductID=4321&Quantity=1
For each value next to ProductID I want to execute some logic. But I am not sure how to get to the values. Any ideas?
When your query string has more than one value with the same key you can use the NameValueCollection.GetValues method which returns a string array:
dim productID as string
for each productID in Page.Request.QueryString.GetValues("ProductID")
' do something with productID
next productID
Here is some untested psuedo code that should work for the code behind on the page. I hope this helps.
dim key as string
dim list as new arraylist()
for each key in Page.Request.QueryString.Keys
if key = "ProductID" then
list.add(Page.Request.QueryString(key))
end if
next key
' do somthing with the list of product id's
Dim productID = Request.Querystring("ProductID")
Dim quantity = Request.Querystring("Quantity")
Try this one. Only works in VB9.
Dim queryString = GetQueryString()
queryString = queryString.SubString(1) 'Remove ?
Dim ids = queryString. _
Split("&"c). _
Select(Function(x) x.Split("="c)). _
Where(Function(x) x(0) = "ProductId" ). _
Select(Function(x) x(1))
Dim sQS as String = Request.QueryString.ToString
For Each eItem In Split(sQS, "&")
Dim sName As String = Left(eItem, InStr(eItem & "=", "=") - 1)
Response.Write(sName _
& " = " & Request.QueryString(sName) _
& "<br>")
Next
and this is shorter but based on the same idea
For Each Key As String In Request.QueryString.Keys
Response.Write(Key & " = " & Request.QueryString(Key) & "<br>")
Next
For read Value of get Parameter use Request.QueryString.Item("param")