Dynamically Adding data to jagged array? - asp.net

I have a recursive function that creates a list of items based on their hierarchy(integer is used to determine which level 1 to 10 max). There can be x number of items in any given level. I want to store all the items that belong the same level at the corresponding index of the jagged array. The items aren't retrieved based on their level so the level can be jumping around all of over the place as the function recurses.
Function RecurseParts(lngPartID1, lngLevel) As Object
'this function will recursivley print the parts lists for the part ID passed in
If IsNumeric(lngPartID1 & "") Then
Dim objRSTemp As Object = Server.CreateObject("ADODB.Recordset")
objRSTemp.CursorLocation = adUseClient
objRSTemp.Open(PART_LIST_SQL & lngPartID1, objConn, adOpenForwardOnly, adLockReadOnly)
'objRSTemp.ActiveConnection = Nothing
If objRSTemp.eof And objRSTemp.bof Then
'PROBLEM, WE HAVE NO RECORDS
Response.Write("There Were No Parts For This Assembly (Part ID #:" & lngPartID1 & ")")
Else
'make output
Dim strTemp As String = String.Empty
If lngLevel <> 1 Then strTemp = " style=""display: none;"">"
Response.Write("<table id='tblparts" & lngCurrentLineNum & "' border=""0"" cellspacing=""0"" width=""100%"" cellpadding=""1"" " & strTemp)
Do Until objRSTemp.EOF
'increase the current line num
lngCurrentLineNum = lngCurrentLineNum + 1
'get current Part ID
lngCurrentPartID = objRSTemp("PartID").value
'reset flag
blnIsAssm = False
'loop thru array of assemblies to see if this is a parent
For ctr = 0 To UBound(arrAssmList, 2)
If arrAssmList(0, ctr) = lngCurrentPartID Then
'the current part is an assembly
blnIsAssm = True
Exit For
ElseIf arrAssmList(0, ctr) > lngCurrentPartID Then
Exit For
End If
Next
If blnIsAssm Then
'recurse these parts
If RecurseParts(objRSTemp("PartID").value, lngLevel + 1) = True Then
'awesome
End If
End If
objRSTemp.MoveNext()
Loop
Response.Write("</table>")
End If
If objRSTemp.State Then objRSTemp.Close()
objRSTemp = Nothing
'RETURN FUNCTION
RecurseParts = True
Else
'no PART ID passed in
Response.Write("No Part ID Passed In")
RecurseParts = False
End If
End Function

It sounds like a Dictionary would work here.
Dim myDict As New Dictionary(Of Integer, List(Of String))
In your recursive function. The parts in the {} are the parts you have to supply.
'this builds the keys as you go
If Not myDict.ContainsKey({{key} -> your Integer}) Then
'add key and use the From statement to add a value if know at this time
myDict.Add({key}, New List(Of String) From {value})
Else
myDict({key}).Add({string to insert at this level})
End If
List of keys in reverse order:
Dim keys = myDict.Keys.OrderByDescending(Function(k) k)

I was able to create a List to store all the partIDs and their levels.
Dim arrSubID As New List(Of List(Of Integer))()
Function RecurseParts(paramenters)
For ctr = 0 To UBound(arrAssmList, 2)
If arrAssmList(0, ctr) = lngCurrentPartID Then
'checks whether we need a new index in the list
If lngLevel + 1 > arrSubID.Count Then
arrSubID.Add(New List(Of Integer))
End If
'adds the partID where it belongs!
arrSubID(lngLevel).Add(lngCurrentPartID)
blnIsAssm = True
Exit For
ElseIf arrAssmList(0, ctr) > lngCurrentPartID Then
Exit For
End If
Next
End Function

Related

No value given one or more required parameters

What's wrong with my code. All i want is that if I click rdbNormal (a RadioButton) then select "A" in cmbBuilding (a ComboBox), all the RoomNo having roomtype "normal" and building "A" will be displayed.
Here's my code
Try
cn.Open()
If rdbNormal.Checked = True Then
Dim DataSet As New DataSet
Dim DataTable As New DataTable
Dim DataAdapter As New OleDbDataAdapter("SELECT * FROM RoomTable Where Building = '" & cmbBuilding.Text & "' and RoomType = Normal ", cn)
DataAdapter.Fill(DataTable)
If DataTable.Rows.Count > 0 Then
With cmbRoomNo
.Items.Clear()
For i As Integer = 0 To DataTable.Rows.Count - 1
.Items.Add(DataTable.Rows(i).Item(3))
Next
.SelectedIndex = -1
End With
End If
DataTable.Dispose()
DataAdapter.Dispose()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
cn.Close()
In your query you have
... and RoomType = Normal
Since Normal is not quoted it is being treated like a parameter placeholder. If you want to match the literal value then put quotes around it:
... and RoomType = 'Normal'

How to insert values of string builder to an Integer Stack? (VB.Net)

This code basically takes a mathematical expression and evaluates it.
The following code i have written in VB.net shamelessly taken from here : Expression Evaluation
which has been written in Java.
Public Function evaluate(expression As [String]) As Integer
Dim tokens As Char() = expression.ToCharArray()
' Stack for numbers: 'values'
Dim values As New Stack(Of UInteger)()
' Stack for Operators: 'ops'
Dim ops As New Stack(Of Char)()
For i As Integer = 0 To tokens.Length - 1
' Current token is a whitespace, skip it
If tokens(i) = " "c Then
Continue For
End If
' Current token is a number, push it to stack for numbers
If tokens(i) >= "0"c AndAlso tokens(i) <= "9"c Then
Dim sbuf As New StringBuilder(100)
'Dim sbuf As New String("", 128)
' There may be more than one digits in number
If i < tokens.Length AndAlso tokens(i) >= "0"c AndAlso tokens(i) <= "9"c Then
sbuf.Append(tokens(System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)))
End If
If sbuf Is Nothing AndAlso sbuf.ToString().Equals("") Then
Else
Dim intgr As Integer
Dim accpt As Boolean = Integer.TryParse(sbuf.ToString(), intgr)
If accpt = True Then
values.Push([Integer].Parse(sbuf.ToString()))
Else
Dim space As String = " "
values.Push(space)
End If
End If
' Current token is an opening brace, push it to 'ops'
ElseIf tokens(i) = "("c Then
ops.Push(tokens(i))
' Closing brace encountered, solve entire brace
ElseIf tokens(i) = ")"c Then
While ops.Peek() <> "("c
values.Push(applyOp(ops.Pop(), values.Pop(), values.Pop()))
End While
ops.Pop()
' Current token is an operator.
ElseIf tokens(i) = "+"c OrElse tokens(i) = "-"c OrElse tokens(i) = "*"c OrElse tokens(i) = "/"c Then
' While top of 'ops' has same or greater precedence to current
' token, which is an operator. Apply operator on top of 'ops'
' to top two elements in values stack
While Not ops.Count = 0 AndAlso hasPrecedence(tokens(i), ops.Peek())
values.Push(applyOp(ops.Pop(), values.Pop(), values.Pop()))
End While
' Push current token to 'ops'.
ops.Push(tokens(i))
End If
Next
' Entire expression has been parsed at this point, apply remaining
' ops to remaining values
While Not ops.Count = 0
values.Push(applyOp(ops.Pop(), values.Pop(), values.Pop()))
End While
' Top of 'values' contains result, return it
Return values.Pop()
End Function
Public Function hasPrecedence(op1 As Char, op2 As Char) As [Boolean]
If op2 = "("c OrElse op2 = ")"c Then
Return False
End If
If (op1 = "*"c OrElse op1 = "/"c) AndAlso (op2 = "+"c OrElse op2 = "-"c) Then
Return False
Else
Return True
End If
End Function
' A utility method to apply an operator 'op' on operands 'a'
' and 'b'. Return the result.
Public Function applyOp(op As Char, b As Integer, a As Integer) As Integer
Select Case op
Case "+"c
Return a + b
Case "-"c
Return a - b
Case "*"c
Return a * b
Case "/"c
If b = 0 Then
'Throw New UnsupportedOperationException("Cannot divide by zero")
End If
Return a \ b
End Select
Return 0
End Function
this is how im using the code :
formula = "10 + 2 * 6"
Dim result As Double = evaluate(formula)
and i keep getting this following error:
Unhandled exception at line 885, column 13 in http:**** DEDOM5KzzVKtsL1tWZwgsquruscgqkpS5bZnMu2kotJDD8R38OukKT4TyG0z97U1A8ZC8o0wLOdVNYqHqQLlZ9egcY6AKpKRjQWMa4aBQG1Hz8t_HRmdQ39BUIKoCWPik5bv4Ej6LauiiQptjuzBMLowwYrLGpq6dAhVvZcB-4b-mV24vCqXJ3jbeKi0&t=6119e399
0x800a139e - Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: Conversion from string " " to type 'UInteger' is not valid.
Im a beginner but i think that the error is occurring because its not able to covert space into integer.How to deal with the spaces??
Any help is much appreciated:).
VB.NET is strongly-typed, so you simply cannot push anything other than integers onto a Stack(Of Integer). Therefore this code:
Dim space As String = " "
values.Push(space)
will always fail at runtime. (By the way, you want to set Option Explicit On and Option Strict On at the top of every module. If you do that, the line above will already be marked as an error at build time).
I haven't tried executing your code, but why would you need to save the spaces if what you're building is an expression evaluator? It doesn't seem to add anything to the evaluation. Perhaps if you simply don't add the spaces to the stack it will work anyway.

Array list error second array replace the first array

I have a problem.
Dim Maxis As String
'Dim MaxisExtra As String
Dim b As New ArrayList
Dim WS As New WebService1.Service1
Dim cnt As String
Dim MRWS As New MobileReload_WS.MobileReload_WS
cnt = WS.StockCountTelco(1, Session("Maxis"))
If CInt(cnt) >= CInt(DropDownList1.SelectedItem.Text) Then
Dim sLock As String
sLock = MRWS.LockAStock(1, 1, "Online", Session("Maxis"), DropDownList1.SelectedItem.Text)
Session("sLock") = sLock
If sLock = "" Then
PopupMsgBox("Unable to allocate Stock")
Else
Maxis = "Maxis" & ";" & Session("Maxis") & ";" & DropDownList1.SelectedItem.Text & ";" & Session("Cost")
'If MaxisExtra = "" Then
' b.Add(Maxis)
' Elseif
' MaxisExtra = MaxisExtra + Maxis
' b.Add(MaxisExtra)
'End If
End If
Else
PopupMsgBox("Not enough stock")
End If
b.Add(Maxis)
Session("Transaction") = b
End Sub
The first time i enter the string into the arraylist it is okay. But when the user press the button add again the second time, it replace the first string. Can anyone help me how to save the string into the second slot based on my coding?
If you're talking about the b ArrayList, then you're creating a new one each time and storing the new ArrayList in Session("Transaction")
Maybe you mean something like this instead...
Dim b as ArrayList = Session("Transaction")
If b Is Nothing Then
b = new ArrayList
End If
...
Session("Transaction") = b
Although it's difficult to say exactly, because your code is very messy and not clear
You put the array list in a session variable, but you never read it back. You create a new array list each time, so it will always be empty and replace the previous one.
Get the array list from the session variable if there is one:
Dim b As ArrayList = Session("Transaction")
If b Is Nothing Then b = New ArrayList

How can i build a new array from object array elements in vb.net?

i'm using vb.net i have the following object array that i'm trung to extract all the true value from give it a name and add it to an array
here is the object array
this is what i have tried so far :
Dim myarray() As String
Dim number As Integer = 0
If resultArray(0).BolComment Then
myarray(number) = "comment"
number = number + 1
End If
If resultArray(0).BolComplete Then
myarray(number) = "complete"
number = number + 1
End If
If resultArray(0).BolFinished Then
myarray(number) = "Finished"
number = number + 1
End If
If resultArray(0).BolOutCome Then
myarray(number) = "OutCome"
number = number + 1
End If
If resultArray(0).BolStatred Then
myarray(number) = "Started"
number = number + 1
End If
If resultArray(0).BolUser Then
myarray(number) = "User"
number = number + 1
End If
this is giving me an error : the variable has been used before
Question how can i extract all the items that have the true value and push it to a new array with giving it a new name
Thanks
I think your problem is that you are not initializing the array to a specific size, nor are you re-sizing it each time you add a new item. However, it would be better to just use the List(T) class:
Dim list As New List(Of String)()
If resultArray(x).BolComment Then
list.Add("comment")
End If
If resultArray(0).BolComplete Then
list.Add("complete")
End If
If resultArray(0).BolFinished Then
list.Add("Finished")
End If
If resultArray(0).BolOutCome Then
list.Add("OutCome")
End If
If resultArray(0).BolStatred Then
list.Add("Started")
End If
If resultArray(0).BolUser Then
list.Add("User")
End If
Then, if you need it as an actual array, do this:
Dim myarray() As String = list.ToArray()

get the value from 2-d arraylist in session

I have an 2-d arraylist with 2 fixed columns and dynamic rows. The arraylist will be assigned to the session variable at the end of the code below. My question is how can loop thorugh the arraylist from the session to get its value?
If .SQLDS.Tables(.sSQLDSTbl).Rows.Count > 0 Then
Dim NoOfAdjType(1, .SQLDS.Tables(.sSQLDSTbl).Rows.Count - 1)
For iRow As Integer = 0 To .SQLDS.Tables(.sSQLDSTbl).Rows.Count - 1
If Not .SQLDS.Tables(.sSQLDSTbl).Rows(iRow).Item("i_commAmt") Is System.DBNull.Value Then
NoOfAdjType(0, iRow) = .SQLDS.Tables(.sSQLDSTbl).Rows(iRow).Item("productType")
NoOfAdjType(1, iRow) = Format(.SQLDS.Tables(.sSQLDSTbl).Rows(iRow).Item("i_commAmt"), "#,##0.00")
End If
Next
Session("iNoOfAdjAmtType") = NoOfAdjType
End If
I have tried this but it's giving me error 'Too many arguments to 'Public Overridable Default Property Item(index As Integer) As Object'
Dim NoOfAdjType As ArrayList = CType(Session("iNoOfAdjAmtType"), ArrayList)
For i As Integer = 0 To NoOfAdjType.Count
Dim a As String = NoOfAdjType(0, i)
Dim b As String = NoOfAdjType(1, i)
Next
The type you are dealing with is Object(,). So when reading from the session you can cast it back to this type.
Here's an article on MSDN which illustrates how to read values from session:
Dim NoOfAdjType as Object(,) = CType(Session("iNoOfAdjAmtType"), Object(,))
' do something with the list
And if you wanted to perform the check safely ensuring that there is an item with the given id in the session:
If Session.Item("iNoOfAdjAmtType") IsNot Nothing Then
' We have a value in the session with the given id
Dim NoOfAdjType as Object(,) = CType(Session("iNoOfAdjAmtType"), Object(,))
End If
I am not certain what is the data-type of array, but this how you manipulate the multi-dimension arrays in VB.NET assuming data-type as object
' declaring variable of multi-dim array
Dim NoOfAdjType As Object(,)
' create array object of needed dimension (you may use redim keyword)
NoOfAdjType = new Object(1, .SQLDS.Tables(.sSQLDSTbl).Rows.Count - 1) {}
...
' push it in session
Session("iNoOfAdjAmtType") = NoOfAdjType
...
' get back from session
NoOfAdjType = DirectCast(Session("iNoOfAdjAmtType"), Object(,))
...
For i As Integer = 0 To NoOfAdjType.GetLength(0)
For j As Integer = 0 To NoOfAdjType.GetLength(1)
Dim a As Object = NoOfAdjType(i, j);
...
Next
Next
See this MSDN article for array in VB.NET: http://msdn.microsoft.com/en-us/library/wak0wfyt.aspx
Try this,
Dim a As String = NoOfAdjType(0)(0,0)
Or use
For Each arr As Object(,) In NoOfAdjType
Next

Resources