Array list error second array replace the first array - asp.net

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

Related

Index was out of range. Must be non-negative and less than the size of the collection - chart databind

I'm trying to build a datatable and then bind it to a gridview and chart object. The gridview appears fine but when I build the x,y array and bind them to the chart object I get the error above.
I've read many forums to understand that the index is looking at a field that is out of range but I've queried in the immediate window all the fields and the are clearly values there. There error occurs as soon as I bind it to the chart object and I don't know why the chart object doesn't just display properly.
This is my aspx codebehind:
Dim dt As DataTable = New DataTable()
dt.Columns.Add("CompanyName")
dt.Columns.Add("Amount")
dt.Columns.Add("Proportion")
Using DBContext As New fundmatrixEntities
Dim queryUnits = (From c In DBContext.Units Where c.SavingApplicationId = savAppId Select New With {.LoanAppId = c.LoanApplicationId}).Distinct().ToList()
Dim companyName As String = ""
Dim savingsAmount As String = ""
Dim totalProportion As String = ""
Dim totalSavingsAmount As String = ""
For Each loan In queryUnits
If Not loan.LoanAppId Is Nothing Then
companyName = classSQLDirect.ExecQuery("SELECT companyname FROM companyprofile where loanapplicationid='" & loan.LoanAppId.ToString & "'")
savingsAmount = classSQLDirect.ExecQuery("SELECT SUM(Amount) from unit where SavingApplicationId='" & savAppId.ToString & "' and LoanApplicationId='" & loan.LoanAppId.ToString & "'")
totalSavingsAmount = classSQLDirect.ExecQuery("SELECT amount FROM SavingApplication WHERE SavingApplicationId='" & savAppId.ToString & "'")
totalProportion = ((savingsAmount / totalSavingsAmount) * 100) & "%"
dt.Rows.Add(companyName, savingsAmount, totalProportion)
End If
Next
gvwBusinesses.DataSource = dt
gvwBusinesses.DataBind()
End Using
Dim x As String() = New String(dt.Rows.Count - 1) {}
Dim y As String() = New String(dt.Rows.Count - 1) {}
For i As Integer = 0 To dt.Rows.Count - 1
x(i) = dt.Rows(i)(0).ToString()
y(i) = dt.Rows(i)(2).ToString()
Next
chart1.Series(0).Points.DataBindXY(x, y)
chart1.Series(0).ChartType = SeriesChartType.Pie
The code errors on the line
chart1.Series(0).Points.DataBindXY(x, y)

How to compare two string in asp.net vb

I am Developing a web apps in Asp.net using vb.net language and i comparing two string using
"=" and
"String.Equals()"
but i get always false result
Dim decod As Decoder = Encoding.UTF8.GetDecoder()
Dim totByt As Byte() = Convert.FromBase64String(Request("numType"))
Dim chrCount As Integer = decod.GetCharCount(totByt, 0, totByt.Length)
Dim deco_char(chrCount) As Char
decod.GetChars(totByt, 0, totByt.Length, deco_char, 0)
Dim str As New String(deco_char)
If str = "MO" Or str.Equals("Mo") Then
//Do somthing
End If
Please see my Watch window output
Please tell me why this give me false condition and how to solve it.
Check out the documentation for String.Equals() and look at the possible values for 3rd parameter comparisionType
String.Equals("MO", str, StringComparison.OrdinalIgnoreCase))
The str variable has a length of 3, instead of 2, causing it to be different than "MO".
Proof:
Dim decod As Decoder = Encoding.UTF8.GetDecoder()
Dim totByt As Byte() = Convert.FromBase64String("TU8=")
Dim chrCount As Integer = decod.GetCharCount(totByt, 0, totByt.Length)
Dim deco_char(chrCount) As Char
decod.GetChars(totByt, 0, totByt.Length, deco_char, 0)
Dim str As New String(deco_char)
Dim result1 = str.StartsWith("MO") ' is true
Dim result2 = str.Equals("MO") ' is false
Dim length = str.Length ' is 3
So obviously str is not the same as "MO".
Remember that if you declare an array like:
Dim deco_char(2) ' an array of 3 elements
...the indexes of the elements range from 0 through 2, so it contains 3 elements.
Solution: if you replace line 4 with:
Dim deco_char(chrCount-1) As Char
.. it will work, because now (in your specific case) your array is of size 2 instead of 3.
Try this :
str.Equals("MO", StringComparison.CurrentCultureIgnoreCase);

Cannot get the last row of data

In my ASP.NET application, i need to read the CSV file and insert into sql server.
and it was strange that it treat the 1st row (column name) as LineNumber=2.
but i found that my code cannot read the last row of the CSV file.
Dim CSV_content As String = ""
Dim CSVFilePathName As String = Server.MapPath("~/XXX/" & filename)
If File.Exists(CSVFilePathName) = True Then
'Response.Write("exists")
Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(CSVFilePathName)
Dim CurrentRecord As String()
afile.TextFieldType = FileIO.FieldType.Delimited
afile.Delimiters = New String() {","}
afile.HasFieldsEnclosedInQuotes = True
Dim LastName As String = ""
Dim FirstName As String = ""
Dim DisplayName As String = ""
Dim EmailName As String = ""
Dim dc As New dcHRISDataContext
' parse the actual file
Do While Not afile.EndOfData
Try
CurrentRecord = afile.ReadFields
'insert into tmp db
If afile.LineNumber > 2 Then
Dim newRecord1 As New XXX
dc.XXX.InsertOnSubmit(newRecord1)
newRecord1.LastName = CurrentRecord(0).Trim
newRecord1.FirstName = CurrentRecord(1).Trim
newRecord1.DisplayName = CurrentRecord(1).Trim
newRecord1.DirEmail = CurrentRecord(3).Trim
newRecord1.GetFileDate = DateTime.Now
newRecord1.GetFileName = filename
dc.SubmitChanges()
End If
Catch ex As FileIO.MalformedLineException
Stop
End Try
Loop
End If
Wow, this is the dumbest issue that I have seen.
Anyhow, Apparently the last row in the TextFieldParser is -1, and not LastRowWithValuesIndex + 1. So what happens is this.
You read the data of the last line (this is fine)
The reader skips to the next line to prepare the next line to read (this is fine)
You get the afile.LineNumber, now set to the next line. Which is -1
at this point. (this is dumb although understandable, not your fault)
Your if statement wont let you in because hey you are on line -1.
Loop ends, skipping last row in the CSV.
All you have to do is to read the line number of the row before reading the data:
Dim i As Integer = afile.LineNumber
CurrentRecord = afile.ReadFields
If i > 2 Then
etc

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

loop through datatable to create a string that looks like this

I want to loop through my datatable column called SDESCR and created a string that looks like this.
Dim labels As String() = {"North", "South", "East", "West", "Up", "Down"}
this is what i am trying and it is not working
Dim labels As String()
For Each row As DataRow In tablegraph.Rows
labels = labels " ' " + row.Item("SDESCR") + " ',"
Next row
THANK YOU FOR THE HELP, I WILL TEST THEM TOMORROW AND SEE WHICH WORKS BEST AND MARK ONE CORRECT.
Do this instead
Dim labels As String()
Dim labelsList As List(Of String) = New List(Of String)
For Each row As DataRow In tablegraph.Rows
labelsList.Add(row.Item("SDESCR"))
Next
labels = labelsList.ToArray()
If you need it to be a comma delimited list instead you can just do
Dim commaLabels As String = String.Join(labels, ",")
If you need them stored in an array, then you can add them to a list and then call the ToArray() method on the list:
Dim labelList As New List(Of String)
For Each row As DataRow In tablegraph.Rows
labelList.Add(row.Item("SDESCR"))
Next row
Dim labels As String() = labelList.ToArray()
If you want a string, use this (string builder is best due to memory management issues with constant string declaration.
Dim labels As New StringBuilder()
For Each row As DataRow In tablegraph.Rows
labels.Append(" ' " + row.Item("SDESCR") + " ',")
Next row
Then when you need the string, use labels.ToString()
If you want an array, use this...
Dim labels As New List(Of String)()
For Each row As DataRow In tablegraph.Rows
labels.Add(row.Item("SDESCR"))
Next row
Then when you need the array, use labels.ToArray()
The main reason your above code is failing is that you are declaring an Array of strings.
If you mean a String-Array instead of a String, this works:
Dim labels(tablegraph.Rows.Count - 1) As String
For i As Int32 = 0 To tablegraph.Rows.Count - 1
labels(i) = tablegraph(i)("SDESCR").ToString
Next
If you want them separated with a comma, you can use a StringBuilder to append:
Dim labels As New System.Text.StringBuilder
For i As Int32 = 0 To tablegraph.Rows.Count - 1
labels.Append(" ' ").Append(tablegraph(i)("SDESCR").ToString).Append(" ',")
Next
If labels.Length <> 0 Then labels.Length -= 1 'remove last comma'
Dim labelString As String = labels.ToString
There are plenty of ways to do this; here is an approach using LINQ
Dim labels As String() = (From myRow In tablegraph _
Select CType(myRow.Item("SDESCR"), String)).ToArray
It's worth nothing that this will fail for NULL/NOTHING values of "SDESCR".
If you just want a single comma-separated values you can do this:
Dim sOutput = String.Join(",", (From myRow In tablegraph _
Select CType(myRow.Item("SDESCR"), String)).ToArray)
labels = labels " ' " + row.Item("SDESCR") + " ',"
^
Plus sign missing?
Also, when you do this you'll be left with an extra , at the end of your string. So you'll want to strip that off.

Resources