"var" variable is used before it is assigned a value - vb.net

It seems like I need to assign some values into variable var() and I don't know how. Can someone help me fix this please.
Imports System
Imports System.IO
Module Module1
Sub Main()
Dim i As Integer
Dim var() As String
Dim lines() As String = IO.File.ReadAllLines("C:\Users\carment\Desktop\Test.txt")
i = 1
For Each line As String In lines
var(i) = line
Console.WriteLine(var(i))
i = i + 1
Next
End Sub
End Module

You have to initialize the array as well:
var = New String(lines.Length-1) {}

Related

Collection to string() convertion in vb.net

I'm a beginner.my question is,
I have an observablecollection(of string)
How can I add those collection's each elements as an array of string elements
Using for loop?
Dim obsv as new observablecollection(of string) // has some collection of string
For each str in obsv
// How can I add that str into string Array
Next
You can use LINQ .ToArray() method. Or use the Item[Int32] property.
Dim s As ObservableCollection(Of String)
' Whatever code to fill that collection.
' First solution:
Dim arr1 = s.ToArray() ' This needs the System.Linq namespace to be imported.
' Second solution:
Dim arr2(s.Count - 1) As String
For i As Integer = 0 To s.Count - 1
arr2(i) = s.Item(i)
Next
And here is a complete working code snippet:
Imports System
Imports System.Collections.ObjectModel
Imports System.Linq
Public Module Module1
Public Sub Main()
Dim s As New ObservableCollection(Of String)()
s.Add("Hello")
s.Add("World")
' Whatever code to fill that collection.
' First solution:
Dim arr1 = s.ToArray() ' This needs the System.Linq namespace to be imported.
Console.WriteLine("First array:")
Console.WriteLine(String.Join(", ", arr1))
Console.WriteLine()
' Second solution:
Dim arr2(s.Count - 1) As String
For i As Integer = 0 To s.Count - 1
arr2(i) = s.Item(i)
Next
Console.WriteLine("Second array:")
Console.WriteLine(String.Join(", ", arr2))
End Sub
End Module
Output is:
First array:
Hello, World
Second array:
Hello, World
Or if you want to use For Each loop, you can do it like that:
Dim arr2(s.Count - 1) As String
Dim i As Integer = 0
For Each str In s
arr2(i) = str
i += 1
Next

Replace exact word

I want to convert this string:
"http://www.example.com/sms.aspx?user=joey&pass=joey123&mbno=9792234567&msg=Test"
to this:
"http://www.example.com/sms.aspx?user={0}&pass={1}&mbno={2}&msg={3}"
But I am getting output like this:
"http://www.example.com/sms.aspx?user={0}&pass={0}123&mbno={2}&msg={3}".
I have used the following line of code for replacing:
Dim SMSUrlStr As String="http://www.example.com/sms.aspxuser=joey&pass=joey123&mbno=9792234567&msg=Test"
e.g. Regex.Replace(SMSUrlStr, joey, {0})
but it is also replacing "joey" from "joey123".
How can I make the replacement more specific?
Instead of looking at the input as a string, you could regard it as a URI. There are methods in the framework to work with URIs, and from that we can rebuild it into the form you need:
Imports System.Collections.Specialized
Imports System.Text
Imports System.Web
Module Module1
Sub Main()
Dim s = "http://www.example.com/sms.aspx?user=joey&pass=joey123&mbno=9792234567&msg=Test"
Dim u = New Uri(s)
Dim q = HttpUtility.ParseQueryString(u.Query)
Dim newQ = q.AllKeys.Select(Function(p, i) p & "={" & i & "}")
Dim newS = u.GetLeftPart(UriPartial.Path) & "?" & String.Join("&", newQ)
Console.WriteLine(newS)
Console.ReadLine()
End Sub
End Module
Outputs:
http://www.example.com/sms.aspx?user={0}&pass={1}&mbno={2}&msg={3}

How to divide a string by another string using Split in VB.Net? [duplicate]

This question already has an answer here:
VB.NET String.Split method?
(1 answer)
Closed 3 years ago.
I am trying to divide a string similar to this:
"<span>1</span> - Selection"
And get the value that is enclosed between the <span>.
In JavaScript I do this:
var example= "<span>1</span> - selection";
var separation= example.replace("</span>","<span>").split("<span>");
console.log("Split: ",separation);
//The result is ["","1"," - Selección"]
console.log("Value that I want: ",separation[1]); //I get the value that I need
And that's it that I need to do but in Visual .NET, but it doesn't work for me.
I try:
Dim WordString As String = "<span>1</span> - Selection"
Dim idSelection As String() = WordString.Replace("</span>","<span>").Split("<span>")
or sending all the </span> replaced in the string to just do:
Dim WordString As String = "<span>1<span> - Selection"
Dim idSelection As String() = WordString.Split("<span>")
But in the position (1) I always get "span>1", and I can't do the split like in JS
How can I do it correctly?
To simulate the code VB.Net use https://dotnetfiddle.net/
The code:
Imports System
Public Module Module1
Public Sub Main()
Dim WordString As String = "<span>1</span> - Selection"
Dim idSelection As String() = WordString.Replace("</span>","<span>").Split("<span>")
Console.WriteLine(idSelection(1))
End Sub
End Module
You have to use Split(String[], StringSplitOptions) to split using a string. So you can use the following solution:
Imports System
Public Module Module1
Public Sub Main()
Dim WordString As String = "<span>1</span> - Selection"
Dim idSelection As String() = WordString.Replace("</span>","<span>").Split({"<span>"}, StringSplitOptions.RemoveEmptyEntries)
Console.WriteLine(idSelection(0))
End Sub
End Module
demo on dotnetfiddle.net
You can also use a solution using a regular expression with a positiv lookahead and lookbehind:
Imports System
Imports System.Text.RegularExpressions
Public Module Module1
Public Sub Main()
Dim rgx As New Regex("(?<=<span>)(.+)(?=</span>)")
Dim WordString As String = "<span>1</span> - Selection"
If rgx.IsMatch(WordString) Then
Console.WriteLine(rgx.Matches(WordString)(0))
End If
End Sub
End Module
demo on dotnetfiddle.net

Setting Values Using Reflection

I am using VB.NET. I have created a small scale test project that works similar to my program. I am trying to say something like: getObjectType(object1) if Object1.getType() = "ThisType" then get the properties. Each object contains an ID and I would like to do this: Object1.Id = -1 (I know it won't be that short or easy). I thought there was a way to do this by using something like: Object1.SetValue(Value2Change, NewValue) but that doesn't work and I'm not sure how to exactly do this. Below is my code. Thank You!
Module Module1
Sub Main()
Dim Db As New Luk_StackUp_ProgramEntities
Dim Obj1 As IEnumerable(Of Stackup) = (From a In Db.Stackups).ToList
Dim Obj2 As IEnumerable(Of Object) = (From a In Db.Stackups).ToList
Dim IdNow As Integer = Obj1(0).IdStackup
Dim StackUpNow As Stackup = (From a In Db.Stackups Where a.IdStackup = IdNow).Single
Console.WriteLine(StackUpNow)
getInfo(StackUpNow)
getInfo(Obj1(0), Obj1(0))
areObjectsSame(Obj1(0), Obj1(67))
switchObjects(Obj1(0), Obj2(1))
getObjectValues(Obj2(55))
Console.WriteLine("========================================")
TestCopyObject(StackUpNow)
ChangeObjectValues(StackUpNow)
Console.ReadKey()
End Sub
Private Sub ChangeObjectValues(Object1 As Object)
Console.WriteLine("Changing Object Values")
Dim myField As PropertyInfo() = Object1.GetType().GetProperties()
'Dim Index As Integer 'Did not find value
'For Index = 0 To myField.Length - 1
' If myField(Index).ToString.Trim = "IdStackup" Then
' Console.WriteLine("Found the ID")
' End If
'Next
If Object1.GetType().Name = "Stackup" Then
'Set the Value
End If
End Sub
You can use PropertyInfo.SetValue to set the value using reflection. You could also use a LINQ SingleOrDefault query to simplify finding the correct PropertyInfo, so you could do something like this:
Private Sub ChangeObjectValues(Object1 As Object)
Console.WriteLine("Changing Object Values")
Dim t As Type = Object1.GetType()
If t.Name = "Stackup" Then
Dim myField As PropertyInfo = t.GetProperties() _
.SingleOrDefault(Function(x) x.Name = "IdStackup")
If myField IsNot Nothing Then
Console.WriteLine("Found the ID")
myField.SetValue(Object1, -1)
End If
End If
End Sub
It's not clear from the question if you really need to use reflection - perhaps a common interface to define the id property, or just type checking and casting, etc. would be better.
Well, I struggled to see how your code example applied to your question, but if you are simply asking how to set the ID of an object using reflection, this code might help you. The trick is that a property is typically handled using a set and a get method.
Imports System.Web.UI.WebControls
Imports System.Reflection
Module Module1
Sub Main()
Dim tb As New Label()
Dim t As Type = tb.GetType()
If TypeOf tb Is Label Then
Dim mi As MethodInfo = t.GetMethod("set_ID")
mi.Invoke(tb, New Object() {"-1"})
End If
Console.WriteLine(tb.ID)
Console.ReadLine()
End Sub
End Module

Function parameter list visual basic

I'm trying to save into a variable the parameters list that I receive in a Function. For example:
Function fTest(xVal1 as Integer, xVal2 as Integer) as String
wListParams = "xVal1:" & xVal 1 & "#" & "xVal2:" & xVal2
End Function
I want to use this list if an error occurs and send a mail.
What I'm looking it's a way for to build this String without writing every case in every function (more than 1000).
Please help!
Thanks!!!
Do you want to concatenate all the parameters together into one string? If so, try this.
Imports System.Text
Public Function BuildParametersString(ByVal ParamArray parameters() As Integer) As String
Dim sb As New StringBuilder()
For i As Integer = 0 To parameters.Count() - 1
sb.Append(String.Format("xVal{0}:{1}#", i + 1, parameters(i)))
Next
Return sb.ToString()
End Function
Private Sub test()
Dim param1 As Integer = 1, param2 As Integer = 2
' passing individual parameters
Dim s1 As String = BuildParametersString(param1, param2)
' passing paramaters in an array
Dim s2 As String = BuildParametersString({param1, param2})
End Sub