Visual Basic .NET Help - vb.net

How can I get this code into a loop?
contact.first_name = list.Item(0)
contact.middle_name = list.Item(1)
contact.last_name = list.Item(2)
contact.age = list.Item(3)
contact.mobile_phone = list.Item(4)
contact.home_phone = list.Item(5)
contact.work_phone = list.Item(6)
contact.home_street = list.Item(7)
contact.home_city = list.Item(8)
contact.home_state = list.Item(9)
contact.home_zip = list.Item(10)
contact.work_street = list.Item(11)
contact.work_city = list.Item(12)
contact.work_state = list.Item(13)
contact.work_zip = list.Item(14)

You can't. Even if you used something like reflection to enumerate the fields in contact and assign them that way, since there's no inherent ordering of those members, you'd still not be able to do the loop.

First, you would need some way to associate index with the name of a property. Probably the best way to do this is to create a list of pairs that store the property name and an index:
Class Info
Public Property Name As String
Public Property Index As Integer
End Class
Then, you'd need to create a list with elements that represent the associations:
Dim associations = {
New Info With { .Name = "first_name", .Index = 0 }, _
New Info With { .Name = "second_name", .Index = 1}, ... }
Now, you could use a simple For loop and Reflection to set the properties:
Dim contType = contact.GetType()
Dim empty As Object(0)
For Each assoc In associations
contType.GetProperty(assoc.Name) _
.SetValue(contact, list.Item(assoc.Index), empty)
Next
I'm not a VB expert and I didn't try the code, but something along these lines should work. Anyway, it really depends on the scenario - in some cases, there is no better way than what you're using currently.

I assume you want to loop list.Item. You can do it but you'll end up with more code than you have already.
For example
For i As Integer = 0 To list.Item.Count - 1
Select Case i
Case 1
contact.middle_name = list.Item(i)
Case 2
contact.last_name = list.Item(i)
Case 3
contact.age = list.Item(i)
...
End Select
Next
As you can see it probably is not worth doing.

If you need it to go to infinity, you probably want a function that takes a contact, a list, and a starting index.
Public Sub FillContact(ByVal contact As Contact, values As IList(Of Object),
startingIndex As Integer)
'error checking here, such as ensuring you have a contact and value
'list and that startingIndex + number of properties < values.Count
contact.first_name = values(startingIndex)
contact.middle_name = values(startingIndex + 1)
'...
contact.work_state = value(startingIndex + 13)
contact.work_zip = value(startingIndex + 14)
End Sub
Then you can call this function in a loop, something like
Dim contacts As New List(Of Contact)
'load the values
Dim values() As Object = GetValues()
For i = 0 To values.Length Step NumberOfProperties
Dim nextContact As New Contact()
FillContact(nextContact, values, i)
contacts.Add(nextContact)
Next

I managed to get it working in a loop statement.
For x As Integer = 1 To list.Count / 15
Dim contact As New Contact
my_contacts.Add(contact)
Next
Dim i As Integer = 0
For Each contact In my_contacts
With contact
.first_name = list.Item(i)
i += 1
.middle_name = list.Item(i)
i += 1
.last_name = list.Item(i)
i += 1
.age = list.Item(i)
i += 1
.mobile_phone = list.Item(i)
i += 1
.home_phone = list.Item(i)
i += 1
.work_phone = list.Item(i)
i += 1
.home_street = list.Item(i)
i += 1
.home_city = list.Item(i)
i += 1
.home_state = list.Item(i)
i += 1
.home_zip = list.Item(i)
i += 1
.work_street = list.Item(i)
i += 1
.work_city = list.Item(i)
i += 1
.work_state = list.Item(i)
i += 1
.work_zip = list.Item(i)
i += 1
End With
Next

Easy, use a ForEach loop to iterate through the members in contact. I am assuming "contact" is a class with all the members listed as being public.
Next use a counter variable (i) to go from 0 to (list.Items.Count - 1). Initialize this counter variable OUTSIDE the ForEach loop.
Then assign the first listitem (When i = 0) to the first member in contact. After assigning, increment i (i+=1) and then close the loop.
Now i will automatically increment each time the loop runs and will assign the required data to the contact member.

Related

Ascending Order Textbox Separated with Comma

I'm new here. I have a textbox,
Textbox1.text = 1,2,7,4,11.
I want to be Output:
1,2,4,7,11.
Textbox1.text = 1,2,7,4,11.
I want to be Output:
1,2,4,7,11.
VB.Net
I found this code and it works for who wants it.
Code:
Private Sub Array()
Dim InputNumbers, SplitInputNumbers, ArrayCount, ReSort, iterInputNum, Num1, Num2
InputNumbers = OutputText1.Text
SplitInputNumbers = Split(InputNumbers, ",")
ArrayCount = UBound(SplitInputNumbers)
ReSort = "YES"
While ReSort = "YES"
ReSort = "NO"
For iterInputNum = 0 To ArrayCount
If iterInputNum < ArrayCount Then
If CInt(SplitInputNumbers(iterInputNum)) > CInt(SplitInputNumbers(iterInputNum + 1)) Then
Num1 = SplitInputNumbers(iterInputNum)
Num2 = SplitInputNumbers(iterInputNum + 1)
SplitInputNumbers(iterInputNum + 1) = Num1
SplitInputNumbers(iterInputNum) = Num2
ReSort = "YES"
End If
End If
Next
End While
Dim iterSortedNum, SortedNumericArray
For iterSortedNum = 0 To ArrayCount
If iterSortedNum = 0 Then
SortedNumericArray = SplitInputNumbers(iterSortedNum)
Else
SortedNumericArray = SortedNumericArray & "," & SplitInputNumbers(iterSortedNum)
End If
Next
OutputText1.Text = (SortedNumericArray)
You could do something like this. It takes your string splits it into an array. Converts each substring into a number, Making a new Integer array. Sorts that new array. and then using join converts it back into a comma separated string
Dim str = "1,2,7,4,11"
Dim b = String.Join(",", str.Split(",").Select(Function(x) Integer.Parse(x.Trim())).OrderBy(Function(x) x))

Bubble Sort List of Items Using Code Not Sort Function

Hi I have a project that requires me to bubble sort a list of patients. How can I do it using this code:
Swapped = True
While Swapped = True
Swapped = False
ComparisonNumber = 0
While ComparisonNumber < PatientCount
If Names(ComparisonNumber) > Names(ComparisonNumber + 1) Then
Temp = Names(ComparisonNumber)
Names(ComparisonNumber) = Names(ComparisonNumber + 1)
Names(ComparisonNumber + 1) = Temp
Swapped = True
End If
ComparisonNumber = ComparisonNumber + 1
End While
End While
where instead of Names() I have a list of items:
Public Class Patient
Public Property Name As String
Public Property Height As Decimal
Public Property Weight As Decimal

Initialize structure

Public Enum eSourceMode
AUS = 0
EIN = 1
End Enum
Public Structure tSourceChannel
Dim OnOff() As eSourceMode
Dim chan_nr As Short
End Structure
I'm trying to set value to
For i = gSources.GetLowerBound(0) To gSources.GetUpperBound(0) Step 1
gSources(i).chan_nr = i
'gSources is 0 based ?
If gSources.GetLowerBound(0) = 0 Then
k = i + 1
Else
k = i
End If
Dim hehe As Integer = gSources.Count
For j = gNoiseBands.GetLowerBound(0) To gNoiseBands.GetUpperBound(0) Step 1
'ab 17.1.2012: gNrSources sets nr of available outputs
If k <= gNrSources Then
gSources(i).OnOff(j) = eSourceMode.EIN
Else
gSources(i).OnOff(j) = eSourceMode.AUS
End If
Next j
Next i
result is exception
System.NullReferenceException occurred
Object reference not set to an instance of an object.
I need this, because I have .ini file and these values :
"gSources0",1,0,1,1,1,1,1
"gSources1",1,1,1,1,1,1,1
"gSources2",1,1,1,1,1,1,1
"gSources3",1,1,1,1,1,1,1
Result of should be for an example :
gSources(0).OnOff(0) = 1 , gSources(0).OnOff(1) = 0
Here you declare that OnOff is an array
Dim OnOff() As eSourceMode
but you never define how large the array should be or assign memory to the array.
'...
Dim hehe As Integer = gSources.Count
'Specify array size
Redim gSources(i).OnOff(gNoiseBands.GetUpperBound(0) - gNoiseBands.GetLowerBound(0))
For j = gNoiseBands.GetLowerBound(0) To gNoiseBands.GetUpperBound(0) Step 1
'...
Next j

Implementing a Variable in a Label Name in VB?

I currently have a huge IF statement and want to minimize it as much as possible.
I have a datagrid that i am populating from a SQL query and then from this datagrid i am passing the values into seperate labels.
I am able to create a For Each Loop in which i cycle through the variables looking until a counter reaches 7. However the problem arises when i need to incremente the Label name values by one. Each time, so essentially i need to add a counter variable into the Label name.
The code that i need to minimize is:
result73 = DataGridView1.Rows(0).Cells(0).Value.ToString
result74 = DataGridView1.Rows(0).Cells(1).Value.ToString
result75 = DataGridView1.Rows(1).Cells(0).Value.ToString
result76 = DataGridView1.Rows(1).Cells(1).Value.ToString
result77 = DataGridView1.Rows(2).Cells(0).Value.ToString
result78 = DataGridView1.Rows(2).Cells(1).Value.ToString
result79 = DataGridView1.Rows(3).Cells(0).Value.ToString
result80 = DataGridView1.Rows(3).Cells(1).Value.ToString
result81 = DataGridView1.Rows(4).Cells(0).Value.ToString
result82 = DataGridView1.Rows(4).Cells(1).Value.ToString
result83 = DataGridView1.Rows(5).Cells(0).Value.ToString
result84 = DataGridView1.Rows(5).Cells(1).Value.ToString
result85 = DataGridView1.Rows(6).Cells(0).Value.ToString
result86 = DataGridView1.Rows(6).Cells(1).Value.ToString
result87 = DataGridView1.Rows(7).Cells(0).Value.ToString
result88 = DataGridView1.Rows(7).Cells(1).Value.ToString
If result73 = "Monday" Then
DaySalesLbl1.Text = result74
ElseIf result73 = "Tuesday" Then
DaySalesLbl2.Text = result74
ElseIf result73 = "Wednesday" Then
DaySalesLbl3.Text = result74
ElseIf result73 = "Thursday" Then
DaySalesLbl4.Text = result74
ElseIf result73 = "Friday" Then
DaySalesLbl5.Text = result74
ElseIf result73 = "Saturday" Then
DaySalesLbl6.Text = result74
ElseIf result73 = "Sunday" Then
DaySalesLbl7.Text = result74
End If
This If Statement goes on for each variable that is declared above.
The Loop I have created looks something like this:
Dim cou As Integer
Dim n As Integer
cou = 0
n = 1
Do Until result74 <> ""
If result73 = cou Then
DaySalesLbl +n = result74
End If
cou = cou + 1
n = n + 1
Loop
But the section DaySalesLbl +n = result74 brings an Error because it looks for a generated method.
If, as I suspect, this is a WinForm project, then you can access the controls by name using the Form.Controls collection, like this:
Dim cou As Integer
Dim n As Integer
cou = 0
n = 1
Do Until result74 <> ""
If result73 = cou Then
Dim l As Label = CType(Me.Controls("DaySalesLbl" & n), Label)
l.Text = result74
End If
cou = cou + 1
n = n + 1
Loop
The Controls collection contains all the controls that are direct children of the form. You can access them by index (e.g. Me.Controls(0)), or by name (e.g. Me.Controls("DaySalesLbl6")). However, the collection stores the list as the base Control type, so you have to cast it to a the specific type before accessing the specific properties. That is why the CType(..., Label) is there in the example.
I would write code as follows:
For i as Integer = 0 to 7
Select Case DataGridView1.Rows(i).Cells(1).Value.ToString
Case "Monday"
Me.Controls("DaySalesLbl" & i+1).Text = DataGridView1.Rows(i).Cells(2).Value.ToString
Case "Tuesday"
Me.Controls("DaySalesLbl" & i+2).Text = DataGridView1.Rows(i).Cells(2).Value.ToString
... etc ...
I did this without the IDE, so I hope I didn't mess anything up, but I hope this sets you in the right direction and helps.

Splitting a String into Pairs

How would I go on splitting a string into pairs of letter in VB?
for example: abcdefgh
split into: ab cd ef gh
I'll throw my hat in the ring:
Dim test As String = "abcdefgh"
Dim results As New List(Of String)
For i As Integer = 0 To test.Length - 1 Step 2
If i + 1 < test.Length Then
results.Add(test.Substring(i, 2))
Else
results.Add(test.Substring(i))
End If
Next
MessageBox.Show(String.Join(" ", results.ToArray))
The following allows for odd length strings. If the string is zero-length, I'm not sure what you'd want to do, you'll want to address that case.
Dim src As String = "abcdef"
Dim size As Integer
If src.Length > 0 Then
If src.Length Mod 2 = 0 Then
size = (src.Length / 2) - 1
Else
size = ((src.Length + 1) / 2) - 1
End If
Dim result(size) As String
For i = 0 To src.Length - 1 Step 2
If i = src.Length - 1 Then
result(i / 2) = src.Substring(i, 1)
Else
result(i / 2) = src.Substring(i, 2)
End If
Next
End If
In C# you would do like this:
Dictionary<String, String> Split(String input)
{
if (input.Count % 2 == 0)
{
Dictionary<string, string> Pairs = new Dictionary( );
for (int L = 0, R = 1; L < input.Count && R <= input.Count; ++L, ++R)
{
Char
Left = input[L],
Right = input[R];
Pairs.Add(
Left.ToString(),
Right.ToString());
}
}
else
{
throw new NotEvenException( );
}
return Pairs( );
}
void Main()
{
var Pairs = Split("ABCDEFGH");
foreach(string Key in Split("ABCDEFGH"))
{
Console.Write("{0}{1}\n", Key, Pairs[Key]);
}
}
/*
Output:
AB
CD
EF
GH
*/
Now, I know what you think: This isn't what I want! But I say: It is actually, at least partly.
Since I presume you're working in VB.net, the basic structure of what you want performed is outlined in the short snippet above.
For example: The method Count (of the object String) exists in both C# and in VB.
Hope it helps a bit at least!