Implementing a Variable in a Label Name in VB? - vb.net

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.

Related

Keep getting a Index was outside the bounds of the array error Visual Basic

I keep getting a "Index was outside the bounds of the array" error when trying to run my code. It points to this line.
If order(i).purchaseMethod = "S" Then
It is in this context
Sub calculatePopularPayment(ByRef popularMethod, ByVal order)
'declares the subclass-specific variables
Dim i As Integer = 0
Dim officeCount As Integer = 0
Dim websiteCount As Integer = 0
For i = 0 To 299
If order(i).purchaseMethod = "S" Then
officeCount = officeCount + 1
ElseIf order(i).purchaseMethod = "W" Then
websiteCount = websiteCount + 1
End If
i = i + 1
Next
Can anybody help me out here?
A For-loop does not need to be incremented manually, the loop itself odes it for you:
For i = 0 To 299
If order(i).purchaseMethod = "S" Then
officeCount = officeCount + 1
ElseIf order(i).purchaseMethod = "W" Then
websiteCount = websiteCount + 1
End If
Next
Of course this will still throw this exception if there are less than 300 items in the array. If you want to iterate all items you should use:
For i = 0 To order.Length - 1
...
Next
If you want to skip every other element you should use Step:
For i = 0 To 299 Step 2
....
Next
Side-note: i strongly recommend to set Option Strict to On.

why i am getting this error "There is no row at position 0 vb.net"?

I am trying to add values from LANG_OBJ.TEXT to DataTableRow.
While adding i am getting a error:
There is no row at position 0
dtsaveTranslate = checkTranslateValues()
lang_id_text CType(Controls.Find("txt_id"True).FirstOrDefault(),TextB`enter code here`ox)
lang_de_text = CType(Controls.Find("txt_de", True).FirstOrDefault(), TextBox)
lang_row = dtsaveTranslate.NewRow()
lang_row("de") = lang_de_text
For Each row As DataRow In dtlang.Rows
lang_iso = Convert.ToString(row("ISO"))
lang_obj = CType(Controls.Find("txt_" + lang_iso, True).FirstOrDefault(), TextBox)
Dim len As Integer = lang_obj.Text.Length
Dim count_de As Integer = lang_de_text.Text.Length
progress.ProgressValue = len + 1
If Convert.ToString(row("isUbersetzen")) = "True" AndAlso lang_iso <> "de" Then
lang_obj.Text = lanClass.GoogleApiTranslate("de", Convert.ToString(row("ISO")), lang_de_text.Text.Trim())
lang_row(lang_iso) = lang_obj.Text
Else
count_txt = 0
End If
Next
dtsaveTranslate.Rows.Add(lang_row)
First you need to make sure that dtLang has rows and then try to loop them!
You need to make sure that dtLang is loaded with data. You should research why it doesn't contain any rows first. From the code above I can't see how the rows are loaded in there. Therefore, the proper check should start with:
If dtlang.Rows.count > 0 '<--- Added a check before looping
For Each row As DataRow In dtlang.Rows
lang_iso = Convert.ToString(row("ISO"))
lang_obj = CType(Controls.Find("txt_" + lang_iso, True).FirstOrDefault(), TextBox)
Dim len As Integer = lang_obj.Text.Length
Dim count_de As Integer = lang_de_text.Text.Length
progress.ProgressValue = len + 1
If Convert.ToString(row("isUbersetzen")) = "True" AndAlso lang_iso <> "de" Then
lang_obj.Text = lanClass.GoogleApiTranslate("de", Convert.ToString(row("ISO")), lang_de_text.Text.Trim())
lang_row(lang_iso) = lang_obj.Text
Else
count_txt = 0
End If
Next
End If

Upper Case in VB 6 text box

How to make first letter in upper case while pressing tab or space in vb 6.0 ?
My code is as follows
txtFirstName.Text = UCase$(txtFirstName.Text)
but it doesn't change after tab or space
It's just simple just do this in the text box keypress events...
Private sub textbox_keypress(KeyAscii As Integer)
KeyAscii = Asc(UCase(Chr(KeyAscii)))
End Sub
Use the LostFocus event
Private Sub yourTextBox_LostFocus()
With yourTextBox
'first letter in upper case, the rest, untouched.
.Text = UCase(Mid(.Text, 1, 1)) & Mid(.Text, 2, Len(.Text))
End With
End Sub
Apply the same logic to the KeyDown event and check if the pressed key is the space key.
Private Sub yourTextBox_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 32 Then
With yourTextBox
'first letter in upper case, the rest, untouched.
.Text = UCase(Mid(.Text, 1, 1)) & Mid(.Text, 2, Len(.Text))
.SelStart = Len(.Text) 'put the cursor at the end of the textbox...
End With
End If
End Sub
StrConv Function
Returns a Variant (String) converted as specified.
Syntax
StrConv(string, conversion, LCID)
The StrConv function syntax has these named arguments:
Part Description
string Required. String expression to be converted.
conversion Required. Integer. The sum of values specifying the type of conversion to perform.
LCID Optional. The LocaleID, if different than the system LocaleID. (The system LocaleID is the default.)
Settings
The conversion argument settings are:
Constant Value Description
vbUpperCase 1 Converts the string to uppercase characters.
vbLowerCase 2 Converts the string to lowercase characters.
vbProperCase 3 Converts the first letter of every word in string to uppercase.
AND THERE IS MORE ...
TO GSERGE
$ means nothing when applied to a function name as opposed to a variable name. VBA uses $ AND B as a suffix to denote similar functionality.
VB6 IS VBA the person who said maybe in VB6 but not in VBA. VB6 program host VBA as their programming language. VB6 on it's own are some app objects and the forms package only - no programming language. It's best to think of VB6 as a VBA host like Office.
If you want to proper case see this WORDBASIC Ver 6 code, (which word 2003 helpfully converted to vba).
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
Public Sub MAIN()
Select Case WordBasic.Int(GetModifer)
Case 0
WordBasic.ChangeCase
Case 1
WordBasic.ChangeCase 4
Case 2
WordBasic.ChangeCase 2
Case 3
ProperCase
Case Else
WordBasic.ChangeCase
End Select
End Sub
Private Sub ProperCase()
Dim F
Dim z
Dim a$
Dim P
F = 1
WordBasic.ChangeCase 2
WordBasic.EditBookmark Name:="SerenityChangeCase", SortBy:=0, Add:=1
z = WordBasic.GetSelEndPos()
WordBasic.CharLeft 1
While WordBasic.GetSelEndPos() < z And Not WordBasic.AtEndOfDocument()
WordBasic.SelectCurWord
a$ = WordBasic.[Selection$]()
P = 0
If LCase(a$) = "a" Then
P = 1
ElseIf LCase(a$) = "an" Then
P = 1
ElseIf LCase(a$) = "as" Then
P = 1
ElseIf LCase(a$) = "at" Then
P = 1
ElseIf LCase(a$) = "be" Then
P = 1
ElseIf LCase(a$) = "by" Then
P = 1
ElseIf LCase(a$) = "in" Then
P = 1
ElseIf LCase(a$) = "is" Then
P = 1
ElseIf LCase(a$) = "of" Then
P = 1
ElseIf LCase(a$) = "on" Then
P = 1
ElseIf LCase(a$) = "or" Then
P = 1
ElseIf LCase(a$) = "to" Then
P = 1
ElseIf LCase(a$) = "and" Then
P = 1
ElseIf LCase(a$) = "are" Then
P = 1
ElseIf LCase(a$) = "for" Then
P = 1
ElseIf LCase(a$) = "the" Then
P = 1
ElseIf LCase(a$) = "from" Then
P = 1
ElseIf LCase(a$) = "what" Then
P = 1
ElseIf LCase(a$) = "with" Then
P = 1
End If
If P = 1 And F = 0 Then WordBasic.Insert LCase(a$)
WordBasic.WordRight 1
F = 0
Wend
WordBasic.WW7_EditGoTo Destination:="SerenityChangeCase"
WordBasic.EditBookmark Name:="SerenityChangeCase", SortBy:=0, Delete:=1
End Sub
Private Function GetModifer()
Dim a
Dim B
Dim c
Dim X
a = GetAsyncKeyState(16)
B = GetAsyncKeyState(17)
c = GetAsyncKeyState(18)
X = 0
If a < 0 Then X = X + 1
If B < 0 Then X = X + 2
If c < 0 Then X = X + 4
GetModifer = X
End Function
OK. Yeah txtFirstName is a good indicator of usage here.. So I'd use (sort of) Title Caps And I'd do it on the Validate event.. So
Private Sub txtFirstName_Validate(Cancel As Boolean)
Dim p As Integer ' i doubt we'll use more than 32K for a name....
Dim mName As String
p = 1
' first off lets trim any leading blanks.. assume NOTHING and make sure its all lower case..
mName = LCase(LTrim(txtFirstName))
Do While p > 0 And p <= Len(txtFirstName) ' start with the first non-blank
Mid(mName, p, 1) = UCase(Mid(mName, p, 1))
p = InStr(p, mName, " ")
If p > 0 And p < Len(mName) Then p = p + 1
Loop
Cancel = False
txtFirstName = mName
End Sub
Works every time, and capitalizes each word.. Didn't add any code to to do TRUE title caps but this is close, and short & easy...

Inserting to table in VB.NET, LINQ to SQL

This is the beginnings of a timetabling algorithm. The problem is with inserting a member into a group, but I have included the whole subroutine here for context. The table "membergroup" has 2 headings, MemberID and GroupID. No error code is thrown, but the table does not receive the new record.
I have gone through it line by line, and the values for iMember_Choice.MemberID and groupID_to_insert are correct.
Dim numberofrooms As Byte = rm.Count
Dim possiblerooms(numberofrooms + 1), possibleroomcounter As Int32
For TimeTableNumber = 1 To Val(NumberOfTimetablesToCreate.Text)
Dim memchoic = (dc.ExecuteQuery(Of memberChoice)("SELECT * FROM MemberChoices ORDER BY NEWID()")).ToList 'Orders list randomly
'sort into array for each rank, so highest ranks are allocated first
Dim Member_choices_Table_ordered_by_rank = From q In memchoic Order By q.Rank
For Each Member_Choice In Member_choices_Table_ordered_by_rank
ProgressBar.Value = ProgressBar.Value + 1
Dim iMember_Choice As memberChoice = Member_Choice
'Dim memactpossibleinstance(maxmemchoicernk, n) As memactvpossibleinstance
For Each room In rm
Dim rmid As Int32 = room.RoomID ' finds rooms activities can be in
If Not (From rom In roomact Where rom.ActivityID = iMember_Choice.ActivityID And rom.RoomID = rmid).FirstOrDefault Is Nothing Then 'finds suitable rooms
possiblerooms(possibleroomcounter) = rmid
possibleroomcounter = possibleroomcounter + 1
End If
Next
'find possible times
Dim roomid_to_insert, current_maximum_rank As Integer
Dim period_to_insert As String = "MonAM"
Dim staffact_that_can_do_this_activity = _
(From q In staffact Where q.ActivityID = iMember_Choice.ActivityID)
For roomcount = 0 To possibleroomcounter - 1 'for each room in roomcount, find rank for room
Dim rmid As Int32 = possiblerooms(roomcount)
For Each time In periods
Dim itime As String = time.Period
Dim Rank As Int16 = member_Error_check_period_count(iMember_Choice.MemberID, itime)
If Not (From rav In rmav Where rav.RoomID = rmid And rav.Period = itime) Is Nothing Then 'room is free
Rank = Rank + 12
Else ' room has an activity
Dim GroupID_now = (From q In instnce Where q.Period = itime And q.RoomID = rmid Select q.GroupID).SingleOrDefault
If GroupID_now <> 0 Then
Dim groupActID_now = (From q In grp Where q.GroupID = GroupID_now Select q.ActivityID).SingleOrDefault
'Dim activity_now = (From q In actv Where q.ActivityID = groupActID_now).SingleOrDefault
If groupActID_now = iMember_Choice.ActivityID Then 'Good, this activity is already on in this room
Rank = Rank + 50
If (From q In memgrp Where q.GroupID = GroupID_now).Count > 4 Then
Rank = Rank - 50
End If
End If
End If
End If
If Rank > current_maximum_rank Then
current_maximum_rank = Rank
roomid_to_insert = rmid
period_to_insert = itime
End If
Rank = 0
Next
possibleroomcounter = 0
Next 'for each room possible
Dim groupID_to_insert As Integer
If (From q In instnce Where q.Period = period_to_insert And q.RoomID = roomid_to_insert).FirstOrDefault Is Nothing Then
groupID_to_insert = insert_ins_group(period_to_insert, roomid_to_insert, iMember_Choice.ActivityID)
Else
groupID_to_insert = (From q In instnce Where q.Period = period_to_insert And q.RoomID = roomid_to_insert Select q.GroupID).SingleOrDefault
End If
'PROBLEM PROBPBLY HERE/////////////////////////////////////
memgrp.InsertOnSubmit(New membergroup With {.MemberID = iMember_Choice.MemberID, .GroupID = groupID_to_insert}) 'PROBLEM PROBABLY HERE
dc.SubmitChanges()
current_maximum_rank = 0
Next 'for each memberchoice
dc.SubmitChanges()
Next 'timetabl no
dc.SubmitChanges()
memgrp is initiated as
Dim memgrp As Table(Of membergroup) = dc.GetTable(Of membergroup)()

Adding rows to a dataGridView dynamically

VB.NET 4.0 framework Windows Forms Application. So I have a DataGridView that I have dropped on my form in designer, set all the columns to readOnly, AllowUserToAddRows = False, AllowUserToDeleteRows = False. Now for the part where it the code is going bad at.
My function Looks Like this:
Private Sub fill_items()
Dim prop As List(Of property_info) = db.property_info.ToList
Dim units As List(Of unit) = db.units.ToList
Dim _year As Integer = System.DateTime.Now.Year
Dim fin As List(Of financial) = db.financials.Where(Function(f) f.Year_start.Value.Year = _year).OrderBy(Function(f) f.transaction_date).ToList
Dim x As Integer = 0
For Each _i In prop
x += 1
Dim _typeName As String = String.Empty
Dim i As property_info = _i
Select Case i.property_type
Case Is = 0
_typeName = "Storage"
Case Is = 1
_typeName = "House/Apartment"
Case Is = 2
_typeName = "Office Space"
End Select
reports1GridView.Rows.Add(_typeName, i.property_Name, " ", " ", " ", " ")
For Each _t In units.Where(Function(f) f.propertyId = i.idProperties)
Dim t As unit = _t
x += 1
For Each trans In fin.Where(Function(F) F.Unit_finId = t.UnitId)
x += 1
Dim _ttype As String = String.Empty
Dim _typeCheck As Integer = 0
Select Case trans.transaction_type
Case Is = 0
_ttype = "Payment Recieved"
_typeCheck = 0
Case Is = 2
_ttype = "Rent Charged"
_typeCheck = 1
Case Is = 3
_ttype = "Deposit"
_typeCheck = 1
Case Is = 20
_ttype = "Late Fee"
_typeCheck = 0
Case Is = 4
_ttype = "Auction Collection"
_typeCheck = 0
Case Is = 5
_ttype = "Auction Fee"
_typeCheck = 2
Case Is = 6
_ttype = "City Tax"
_typeCheck = 0
Case Is = 7
_ttype = "County Tax"
_typeCheck = 0
Case Is = 8
_ttype = "State Tax"
_typeCheck = 0
Case Is = 9
_ttype = "Maintenance"
_typeCheck = 2
End Select
Dim _TypeValue As Decimal = Nothing
Select Case _typeCheck
Case Is = 0
_TypeValue = trans.Amount_Paid
Case Is = 1
_TypeValue = trans.amount_due
Case Is = 2
End Select
Dim _tDate As Date = trans.transaction_date
Dim _tDateString As String = _tDate.ToShortDateString.ToString
reports1GridView.Rows.Add(" ", " ", t.UnitId, _ttype, _tDateString, _TypeValue)
Dim xl As String = String.Empty
Next
Next
Next
End Sub
My problem is that the datagridview is displaying only values in the 0,1,2,3 columns of the gridview.. The Gridview looks correct until it Gets to column 3 which is where the transaction type goes. For some reason the amount that should be in column 5 is being displayed in that column and columns 4 and 5 are being left completely blank.. I looked at the values contained in the variables in the last reports1GridView.Rows.Add of the function and all of the variables are not only correct but in the correct order. So my question is why is this failing...
Supposing that your DataGridView is unbound (meaning that no columns are automatically defined) you need to create the appropriate columns required by your code. Then the Row.Add(item, ....) will work
For example:
Private Sub SetupGrid()
reports1GridView.ColumnCount = 5
reports1GridView.Columns(0).Name = "Type"
.... ' other columns
End Sub
before entering in your main loop call this method to define name and type of your columns