There is no row at position 0 error - asp.net

I have the following code:
Do Until i = dsSalesRep.Tables(0).Rows.Count
strRepID = dsSalesRep.Tables(0).Rows(i)("repID").ToString
strLBP = dsSalesRep.Tables(0).Rows(i)("officename").ToString
strLBPEmail = dsSalesRep.Tables(0).Rows(i)("cemail").ToString
strCCRepEmail = dsSalesRep.Tables(0).Rows(i)("cc1").ToString
strRepName = dsSalesRep.Tables(0).Rows(i)("firstname").ToString & " " & dsSalesRep.Tables(0).Rows(i)("lastname").ToString
strRepEmail = dsSalesRep.Tables(0).Rows(i)("email").ToString
strRepPhone = dsSalesRep.Tables(0).Rows(i)("phone").ToString
searchStr3 = "SELECT * FROM LookupSalesRep WHERE repID='" & strRepID & "'"
Dim SqlAdapter3 As New SqlDataAdapter(searchStr3, myConn2)
Dim dsTerritories As New DataSet
myConn2.Open()
SqlAdapter3.Fill(dsTerritories)
strCountry = dsTerritories.Tables(0).Rows(0)("country").ToString
'strCountry = dsTerritories.Tables(0).Rows.Count.ToString
When I run the web page, though, it gives me the error: There is no row at position 0.
But when I use the code
strCountry = dsTerritories.Tables(0).Rows.Count.ToString
strCountry gets the right number of rows. Please help :(

You are in a loop and at some point the table (dsTerritories.Tables(0)) is null. Check first if the table is null:
If dsTerritories.Tables(0).Rows.Count > 0 Then
strCountry = dsTerritories.Tables(0).Rows(0)("country").ToString
End If

Related

ASP.NET MS chart control: Data points insertion error. Only 2 Y values can be set for this data series. Parameter name: dataSource

I'm getting this error on my MS Chart control:
Data points insertion error. Only 2 Y values can be set for this data series.
Parameter name: dataSource
It occurs on line chartPriceHistory_STATIC.DataBind() in my code below.
I think it has got something to do with the way I'm adding points (AddXY) but can't figure out what it is.
I tried these 2 code options:
Option 1
chartPriceHistory_STATIC.Series(seriesName).Points.AddXY(get3LetterMonth(CDate(row("createdate")).Month) + "-" + CDate(row("createdate")).Year.ToString, {CType(row("price"), Integer), totalobjects})
Option 2
chartPriceHistory_STATIC.Series(seriesName).Points.AddXY(get3LetterMonth(CDate(row("createdate")).Month) + "-" + CDate(row("createdate")).Year.ToString, CType(row("price"), Integer))
chartPriceHistory_STATIC.Series("totalobjects").Points.AddXY(get3LetterMonth(CDate(row("createdate")).Month) + "-" + CDate(row("createdate")).Year.ToString, totalobjects)
Both throw the same error...what am I missing?
Dim mycommand As New SqlCommand("SELECT avgprice, createdate, totalobjects FROM avgprices", myConnection)
Dim dtPrices As New System.Data.DataTable
dtPrices.Columns.Add("price", System.Type.GetType("System.Int32"))
dtPrices.Columns.Add("createdate", System.Type.GetType("System.DateTime"))
dtPrices.Columns.Add("totalobjects", System.Type.GetType("System.Int32"))
Dim dr As System.Data.DataRow
Try
Dim reader As SqlDataReader = mycommand.ExecuteReader()
While reader.Read
dr = dtPrices.NewRow()
dr("price") = reader("price")
dr("createdate") = reader("createdate")
dr("totalobjects") = reader("totalobjects")
dtPrices.Rows.Add(dr)
End While
Catch ex As Exception
End Try
' Initializes a New instance of the DataSet class
Dim myDataSet As DataSet = New DataSet()
'Adds rows in the DataSet
myDataSet.Tables.Add(dtPrices)
chartPriceHistory_STATIC.Series.Clear()
Dim seriesName As String = "Avg price"
chartPriceHistory_STATIC.Series.Add(seriesName)
chartPriceHistory_STATIC.Series(seriesName).XValueMember = "Date"
chartPriceHistory_STATIC.ChartAreas.Add("ChartArea1")
chartPriceHistory_STATIC.Series(seriesName).YValuesPerPoint = 2
chartPriceHistory_STATIC.ChartAreas(0).AxisY.MajorGrid.Enabled = True
chartPriceHistory_STATIC.ChartAreas(0).AxisY.Title = "Price"
Dim totalobjects As Integer = 1
chartPriceHistory_STATIC.Series.Add("Series2")
chartPriceHistory_STATIC.Series("Series2").YAxisType = AxisType.Secondary
chartPriceHistory_STATIC.Series("Series2").XValueMember = "Date"
chartPriceHistory_STATIC.Series("Series2").YValueMembers = "totalobjects"
chartPriceHistory_STATIC.Series("Series2").Name = "totalobjects"
chartPriceHistory_STATIC.Series("totalobjects").ChartType = SeriesChartType.Line
chartPriceHistory_STATIC.Series("totalobjects").ToolTip = "Total objects"
chartPriceHistory_STATIC.Series(0).YAxisType = AxisType.Primary
chartPriceHistory_STATIC.Series(1).YAxisType = AxisType.Secondary
For Each row As DataRow In myDataSet.Tables(0).Rows
totalobjects += 1
'I tried: these 2 options, both generate the same error
chartPriceHistory_STATIC.Series(seriesName).Points.AddXY(get3LetterMonth(CDate(row("createdate")).Month) + "-" + CDate(row("createdate")).Year.ToString, {CType(row("price"), Integer), totalobjects})
chartPriceHistory_STATIC.Series(seriesName).Points.AddXY(get3LetterMonth(CDate(row("createdate")).Month) + "-" + CDate(row("createdate")).Year.ToString, CType(row("price"), Integer))
chartPriceHistory_STATIC.Series("totalobjects").Points.AddXY(get3LetterMonth(CDate(row("createdate")).Month) + "-" + CDate(row("createdate")).Year.ToString, totalobjects)
Next
chartPriceHistory_STATIC.DataSource = myDataSet
chartPriceHistory_STATIC.DataBind()
You need to set the YValueMembers for the "Avg price" series, too.
Add this line (use whatever string you want to plot on Y axis):
chartPriceHistory_Static.Series(seriesName).YValueMembers = "totalobjects"
Add it just before this line:
chartPriceHistory_Static.Series(seriesName).YValuesPerPoint = 2
Also, your name of date/createdate column is inconsistent - you won't see the plots until you correct that.
If you are only adding 1 YValue, you can reduce the YValuesPerPoint down to 1 again, without error.
Tested. Works fine. Cheers!
Instead of using Points.AddXY method try to create point through new class and add them to chart
foreach (var result in data)
{
point = new DataPoint();
point.AxisLabel = result.XData;
point.YValues = new double[] { result.YData };
point.Color = result.Color;
seriesDetail.Points.Add(point);
}

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)

treeview conditional formatting

I have a treeview populating from a data set like this
Dim PrSet As New DataSet()
If lblemail.Text.ToString().Equals("ali.saleem#shakarganj.com.pk") Then
PrSet = PDataset("select distinct PEND,to_char(BPV_DTE,'DD MON YYYY') BPV_DTE,BPV_DTE BPV_DTE1,COUNT from chq_dir order by 3 desc")
Else
PrSet = PDataset("select distinct PEND,to_char(BPV_DTE,'DD MON YYYY') BPV_DTE,BPV_DTE BPV_DTE1,COUNT from chq_dte order by 3 desc")
End If
TreeView2.Nodes.Clear()
For Each dr As DataRow In PrSet.Tables(0).Rows
Dim tnParent As New TreeNode()
tnParent.Text = dr("PEND").ToString()
tnParent.Value = dr("BPV_DTE")
tnParent.PopulateOnDemand = True
tnParent.SelectAction = TreeNodeSelectAction.Select
tnParent.ToolTip = tnParent.Text
tnParent.Expand()
TreeView2.Nodes.Add(tnParent)
If dr("COUNT").ToString() = "0" Then
TreeView2.Font.Bold= True
End If
Next dr
There is Column COUNT in which there is 0 in some dates.Problem is that i am trying to bold the treeview where COUNT is 0 but it is not working Any one can give me clear idea to do so.
I have solved My Question Like this
If Not dr("COUNT") = 0 Then
tnParent.Text = "<b>" & dr("PEND").ToString() & "</b>"
End If
I hope I've gethered what you meant by this question...
For Each tn As TreeNode In treeView2.Nodes
If tn.Text = "0" Then
Dim index As Integer
index = tn.Index
treeView2.Nodes(index).NodeFont = New Font(treeView2.Font, FontStyle.Bold)
End If
Next
Apply the style to tnparent and do this before adding the node to parent in treeview, and also from your code it looks like you are changing the fonts to italic not bold.

Copy records to another recordset using Active Server Page

I'm programming in Classic ASP. I'm trying to do the paging. My backend is SQL CE 3.5. Unfortunetly, it doesn't support paging in SQL Query (Like row_number() in sql server).
So I go with ASP Paging. But when i ask to the recordset, give me the first 10 records by setting the rs.PageSize and rs.AbsolutePage and all, it gives me all records. So I planned to copy only first 10 rows from the resultant recordset to another new recordset. So I coded like below:
Set rsTemp = CopyRecordsetStructure(objRs)
rsTemp.Open
iRecordsShown = 0
Set objFields = objRs.Fields
intFieldsCount = objFields.Count-1
Do While iRecordsShown < intPageSize And Not objRs.EOF
rsTemp.AddNew
For Idx = 0 To intFieldsCount
rsTemp.Fields(Idx).Value = objRs.Fields(Idx).Value
Next
rsTemp.Update
iRecordsShown = iRecordsShown + 1
objRs.MoveNext
Loop
Public Function CopyRecordsetStructure(ByVal rs)
Dim rsTemp
Set rsTemp = CreateObject("ADODB.Recordset")
Set objFields = rsTemp.Fields
intFieldCount = objFields.Count - 1
For Idx = 0 To intFieldCount
rsTemp.Fields.Append objFields(Idx).Name, _
objFields(Idx).Type, _
objFields(Idx).DefinedSize
Next
Set CopyRecordsetStructure = rsTemp
End Function
The issue is i could not open the" rsTemp". It throws me error
The connection cannot be used to perform this operation. It is either closed or invalid in this context.
If I use some dummy query and connection it doesn't work.
Please help to copy the records from one recordset to another new record set.
Thanks in advance
Ganesh.
Not sure, but this looks wrong
Set objFields = rsTemp.Fields
Shouldn't it be
Set objFields = rs.Fields
With the comments and fixed in the above comments, the function should be updated Set objFields = rs.Fields to:
Usage:
Dim rsTemp
Set rsTemp = CopyRecordset(rsPadicon)
Update Code
Public Function CopyRecordset(rs)
Dim rsTemp, objFields, intFieldsCount, intPageSize
Set rsTemp = CopyRecordsetStructure(rs)
rsTemp.Open
Set objFields = rs.Fields
intFieldsCount = objFields.Count-1
response.write("<li> rs.RecordCount :" & rs.RecordCount & "</li>")
' response.write("<li> intFieldsCount :" & intFieldsCount & "</li>")
rs.MoveFirst
Do While Not rs.EOF
rsTemp.AddNew
Dim i
For i = 0 to intFieldsCount 'use i as a counter
' response.write("<li> Name :" & rs.Fields(i).Name & "</li>")
' response.write("<li> Value :" & rs.Fields(i).Value & "</li>")
if Not IsNull(rs.Fields(i).Value) then
rsTemp.Fields(i).Value = rs.Fields(i).Value
End if
Next
rsTemp.Update
rs.MoveNext
Loop
Set CopyRecordset = rsTemp
End Function
Public Function CopyRecordsetStructure(ByVal rs)
Dim rsTemp, objFields, intFieldCount, Idx
Set rsTemp = CreateObject("ADODB.Recordset")
Set objFields = rs.Fields
intFieldCount = objFields.Count - 1
For Idx = 0 To intFieldCount
rsTemp.Fields.Append objFields(Idx).Name, _
objFields(Idx).Type, _
objFields(Idx).DefinedSize
Next
Set CopyRecordsetStructure = rsTemp
End Function

ASP.Net String Split not working

Here's my code
Dim RefsUpdate As String() = Session("Refs").Split("-"C)
Dim PaymentsPassedUpdate As String() = Session("PaymentsPassed").Split("-"C)
Dim x as Integer
For x = 1 to RefsUpdate.Length - 1
Dim LogData2 As sterm.markdata = New sterm.markdata()
Dim queryUpdatePaymentFlags as String = ("UPDATE OPENQUERY (db,'SELECT * FROM table WHERE ref = ''"+ RefsUpdate(x) +"'' AND bookno = ''"+ Session("number") +"'' ') SET alpaid = '"+PaymentsPassedUpdate(x) +"', paidfl = 'Y', amountdue = '0' ")
Dim drSetUpdatePaymentFlags As DataSet = Data.Blah(queryUpdatePaymentFlags)
Next
I don't get any errors for this but it doesn't seem to working as it should
I'm passing a bookingref like this AA123456 - BB123456 - CC123456 - etc and payment like this 50000 - 10000 - 30000 -
I basically need to update the db with the ref AA123456 so the alpaid field has 50000 in it.
Can't seem to get it to work
Any ideas?
Thanks
Jamie
I'm not sure what isn't working, but I can tell you that you are not going to process the last entry in your arrays. You are going from 1 to Length - 1, which is one short of the last index. Therefore, unless your input strings end with "-", you will miss the last one.
Your indexing problem mentioned by Mark is only one item, but it will cause an issue. I'd say looking at the base your problem stems from not having trimmed the strings. Your data base probably doesn't have spaces leading or trailing your data so you'll need to do something like:
Dim refsUpdateString as string = RefsUpdate(x).Trim()
Dim paymentsPassedUpdateString as string = PaymentsPassedUpdate(x).Trim()
...
Dim queryUpdatePaymentFlags as String = ("UPDATE OPENQUERY (db,'SELECT * FROM table WHERE ref = ''" & refsUpdateString & "'' AND bookno = ''" & Session("number") & "'' ') SET alpaid = '" & paymentsPassedUpdateString & "', paidfl = 'Y', amountdue = '0' ")
Also, I would recommend keeping with the VB way of concatenation and use the & character to do it.

Resources