ASP.Net get columns with values, add them and then divide - asp.net

I've got some code which is working as it should but it just seems like a bit of a round about way in doing it and wondered if anyone had any ideas of how to tidy it up
Here's my code
Dim TotalNumber As Double
Dim NumberFilled As String
NumberFilled = Nothing
For x = 0 To drCode2a.Tables(0).Columns.Count - 1
If Not drCode2a.Tables(0).Rows(0)(x).ToString() = "0" Then
NumberFilled += drCode2a.Tables(0).Rows(0)(x).ToString() & "-"
TotalNumber = TotalNumber + drCode2a.Tables(0).Rows(0)(x).ToString()
End If
Next
Dim delimiters As Char() = New Char() {"-"c}
Dim TotalNumberFilled As String() = NumberFilled.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
Dim AverageRating As Double = TotalNumber / TotalNumberFilled.Length
Response.Write(NumberFilled & "<br/>" & TotalNumber & "<br/>" & AverageRating)
Basically for my example NumberFilled = "1-2-" and TotalNumber = 3 and AverageRating = 1.5
It shows that 2 columns were filled out and the total they equal is 3 so the average = 1.5
As I said it works like it should but I'd like to tidy up if possible
Thanks

Dim totalNumber as Double = 0
Dim count as Integer = 0
For x = 0 To drCode2a.Tables(0).Columns.Count - 1
Dim current as Double = 0
If Double.TryParse(drCode2a.Tables(0).Rows(0)(x).ToString(), current) AndAlso current <> 0 Then
count += 1
totalNumber += current
End If
Next
Dim averageRating as Double = totalNumber / count

Here is an alternative. I don't know that it's necessarily better, but it does make use of the StringBuilder object which is a little faster than strings and it keeps the total values as doubles rather than performing double to string to double conversions.
Dim NumberFilled As New StringBuilder("")
Dim TotalNumber as Double
Dim ColumnsFilled as Integer = 0
For each column as DataColumn in drCode2a.Tables(0).Columns
Dim value = drCode2a.Tables(0).Rows(0)(column.ColumnName).ToString()
If Not "0".Equals(value, StringComparison.OrdinalIgnoreCase) Then
If NumberFilled.Length > 0 Then NumberFilled.Append("-")
NumberFilled.Append(value)
TotalNumber = Convert.ToDouble(value)
ColumnsFilled += 1
End If
Next

Related

Reset pagesize for each record iText

I am trying to reset the pagesize of each record in pdf, which is the total page
(1 of pagesize
2 of pagesize.......)
The 1st blockcode work for 1 single record but then when it come to multiple record it showed:
1 of 0 //1st record
2 of 0
1 of 0 //2nd record
.......
I think there is something to do with document.setPageSize() but it is boolean and belong to Rectangle.
Please help me solve this problem.
Thank.
Public Overrides Sub onEndPage(ByVal writer As PdfWriter, ByVal document As Document)
Dim page As Rectangle = document.getPageSize()
Dim cb As PdfContentByte = writer.getDirectContent()
Dim arialbasefont As BaseFont = arial.getBaseFont
Dim pg As Rectangle = document.getPageSize()
Dim pageNumberText As String = "Page " & writer.getPageNumber() & " of "
Dim timeStampText As String = Now.ToString
Dim pageNumberTextLength As Double = arialbasefont.getWidthPoint(pageNumberText, footerFontSize)
Dim timeStampTextLength As Double = arialbasefont.getWidthPoint(timeStampText, footerFontSize)
Dim pageNumberTextLeft As Double = 20
Dim templateLeft As Double = pageNumberTextLeft + pageNumberTextLength
Dim pageNumberTextBottom As Double = 5 + footerFontSize
cb.beginText()
cb.setFontAndSize(arialbasefont, footerFontSize)
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, pageNumberText, pageNumberTextLeft, pageNumberTextBottom, 0)
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, Now, pg.urx - (timeStampTextLength + 20), pageNumberTextBottom, 0)
cb.endText()
cb.addTemplate(tpl, templateLeft, pageNumberTextBottom)
End Sub
For Each ProjectID In array
Dim rptRequestReportObj As New rptRequestReport2
rptRequestReportObj.Report(document, ProjectID)
document.newPage()
document.setPageCount(1)
Next ProjectID

How to insert a new row between another rows in gridview boundfield?

I have a gridview like below picture:
In this gridview I want to introduce a new row that does not have any completely out of the cell where the last "Grand Total" there to put a variable mine.
But the question is, how introduce a new row among others?
My code is:
Dim Qty As Double = 0
Dim CostCategory As Double = 0
Dim AssemblyDate As String = Nothing
If GridView1.Rows.Count <> 0 Then
For x As Integer = 0 To GridView1.Rows.Count - 1
For y As Integer = 0 To GridView1.Columns.Count - 1
If y = 0 And GridView1.Rows(x).Cells(1).Text = AssemblyDate Then
GridView1.Rows(x).Cells(1).Text = ""
End If
If GridView1.Rows(x).Cells(1).Text <> Nothing Then
AssemblyDate = GridView1.Rows(x).Cells(1).Text
End If
If y = "9" Then
Qty = Convert.ToDouble(GridView1.Rows(x).Cells(9).Text)
End If
If y = "13" Then
CostCategory = Convert.ToDouble(GridView1.Rows(x).Cells(13).Text)
End If
If y = "14" Then
GridView1.Rows(x).Cells(14).Text = Qty * CostCategory
GridView1.Rows(x).Cells(14).HorizontalAlign = HorizontalAlign.Center
End If
If GridView1.Rows(x).Cells(y).Text = "Yes" Then
GridView1.Rows(x).Cells(y).BackColor = System.Drawing.Color.LawnGreen
ElseIf GridView1.Rows(x).Cells(y).Text = "No" Then
GridView1.Rows(x).Cells(y).BackColor = System.Drawing.Color.Red
End If
Next
Next
End if
before that code i have a query where i fill my gridview:
Dim myQuery As String = SelectQuery & WhereQuery
SqlDataSource1.SelectCommand = myQuery
SqlDataSource1.DataBind()
GridView1.DataSourceID = "SqlDataSource1"
GridView1.DataBind()
Thanks a lot!
Try using this
DataRow dr = tblTable.NewRow(); //Create New Row
dr["ColumnName"] = "Legs"; // Set Column Value
tblTable.Rows.InsertAt(dr, 11); // InsertAt specified position
For VB.Net Grid View
Dim rowNumber As Integer = dGrid.CurrentCell.RowNumber() + 1
Dim myNewRow As DataRow = myDataTable.NewRow()
myDataTable.Rows.InsertAt(myNewRow, rowNumber)
myDataTable.AcceptChanges()

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 iterate between two datatables in ASP.NET

I have two datatables (dtSF and CurveFitTable) that contain two different values which I have to multiply. The objective is to produce a datatable that contains the product of two values from two different datatables. The twist is, the CurveFitTable came from different csv files in a directory which I already defined.
What I intended to do is to have a datatable like the adjustedCopy table in the image below. Unfortunately, what I'm getting is a single datatable which kept on being overwritten and whenever I attempt to databind it to the grid, the datatable seems to be empty. Please help. T.T
This is my code:
Dim adjusteddemandtable As New DataTable()
Dim adjustedcopy As New DataTable()
Dim multiply_SF As Double
Dim adjusted_Demand As Double
Dim initial_Demand As Double
Dim basecurvestamp As Date
adjusteddemandtable.Columns.Add("Base Curve", GetType(Date))
adjusteddemandtable.Columns("Base Curve").SetOrdinal(0)
adjusteddemandtable.Columns.Add("Adjusted_Demand", GetType(Double))
Dim CurveFitTatble As New DataTable()
Try
For Each filename As String In System.IO.Directory.GetFiles(BackUpDirectory)
CurveFitTatble = GetDataTabletFromCSVFile(filename)
For Each row2 As DataRow In dtSF.Rows()
For Each row As DataRow In CurveFitTatble.Rows()
initial_Demand = row(1)
basecurvestamp = row(0)
multiply_SF = row2(0)
adjusted_Demand = multiply_SF * initial_Demand
Dim rowa As DataRow = adjusteddemandtable.Rows.Add()
rowa(0) = basecurvestamp
rowa(1) = adjusted_Demand
Next
Next
adjustedcopy.Merge(adjusteddemandtable, True, MissingSchemaAction.AddWithKey)
Next
GridView1.DataSource = adjustedcopy
GridView1.DataBind()
Catch ex As Exception
ErrorMessageBox(ex.Message)
End Try
I think, I'm missing something or overlooked an important step. Please advise. Thanks in advance.
I just did what #jmcilhinney told me (that is to replace nested Foreach nested loop. Here is my new code (and fortunately, it is working as its expected output requires)
Try
Dim y As Integer = System.IO.Directory.GetFiles(BackUpDirectory).Length
Dim row1 As DataRow
Dim i As Integer = 0
While i < y
row1 = dtSF.Rows(i)
Dim filenames As String() = System.IO.Directory.GetFiles(BackUpDirectory)
Dim filename As String = filenames(i)
multiply_SF = row1(0)
CurveFitTatble = New DataTable()
Dim TS_Name As String = "TmeStamp" + "_" & i
Dim AD_Name As String = "AdjustedDemand" + "_" & i
If i = 0 Then
adjusteddemandtable.Columns.Add(TS_Name, GetType(Date))
adjusteddemandtable.Columns(TS_Name).SetOrdinal(i)
adjusteddemandtable.Columns.Add(AD_Name, GetType(Double))
adjusteddemandtable.Columns(AD_Name).SetOrdinal(i + 1)
ElseIf i > 0 Then
adjusteddemandtable.Columns.Add(TS_Name, GetType(Date))
adjusteddemandtable.Columns(TS_Name).SetOrdinal(i + 1)
adjusteddemandtable.Columns.Add(AD_Name, GetType(Double))
adjusteddemandtable.Columns(AD_Name).SetOrdinal(i + 2)
End If
'If row1(0) = filename Then
CurveFitTatble = GetDataTabletFromCSVFile(filename)
'For Each row As DataRow In CurveFitTatble.Rows()
Dim row As DataRow
For j As Integer = 0 To CurveFitTatble.Rows.Count - 1
row = CurveFitTatble.Rows(j)
initial_Demand = row(1)
basecurvestamp = row(0)
adjusted_Demand = multiply_SF * initial_Demand
Dim rowa As DataRow = adjusteddemandtable.Rows.Add()
If i = 0 Then
rowa(i) = basecurvestamp
rowa(i + 1) = adjusted_Demand
ElseIf i > 0 Then
rowa(i + 1) = basecurvestamp
rowa(i + 2) = adjusted_Demand
End If
Next
i = i + 1
End While
Catch ex As Exception
ErrorMessageBox(ex.Message)
End Try

Averaging columns in a table - ignoring certain columns

I've the following code which successfully makes an average for all the columns from a table. What I need to do though is ignore certain columns in this equation.
Dim totalNumber as Double = 0
Dim count as Integer = 0
For x = 0 To xyz123.Tables(0).Columns.Count - 1
Dim current as Double = 0
If Double.TryParse(xyz123.Tables(0).Rows(0)(x).ToString(), current) AndAlso current <> 0 Then
count += 1
totalNumber += current
End If
Next
Dim averageRating as Double = totalNumber / count
Using your source code you can try this
Dim totalNumber as Double = 0
Dim count as Integer = 0
For x = 0 To xyz123.Tables(0).Columns.Count - 1
Dim current as Double = 0
If Double.TryParse(xyz123.Tables(0).Rows(0)(x).ToString(), current) AndAlso current <> 0 AndAlso x <> 13 AndAlso x <> 1 Then
count += 1
totalNumber += current
End If
Next
Dim averageRating as Double = totalNumber / count
In the above example this will ignore columns 14 and 2 in your average
Hope this helps
If you want to exclude certain columns by name e.g. columns named "weather" then test for Columns(x).ColumnName in your code:
Dim totalNumber as Double = 0
Dim count as Integer = 0
For x = 0 To xyz123.Tables(0).Columns.Count - 1
If Not xyz123.Tables(0).Columns(x).ColumnName="weather" Then
Dim current as Double = 0
'etc

Resources