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

Related

I can't FindControl in the more efficient way during RowDataBound event

I am working on filling two different labels from VB code behind. I currently have this working but I believe there is a much more efficient and better way of doing it. This is the only way I can find my labels without getting a Null reference exception. Again this works but what it does is go through each row multiple times (because of For Each Row....)
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
For Each Row As GridViewRow In GridView1.Rows
Dim HFO1AD As String = DirectCast(Row.FindControl("HFO1AD"), HiddenField).Value
Dim HFO2AD As String = DirectCast(Row.FindControl("HFO2AD"), HiddenField).Value
Dim HFO3AD As String = DirectCast(Row.FindControl("HFO3AD"), HiddenField).Value
Dim HFO4AD As String = DirectCast(Row.FindControl("HFO4AD"), HiddenField).Value
Dim HFO5AD As String = DirectCast(Row.FindControl("HFO5AD"), HiddenField).Value
Dim HFO6AD As String = DirectCast(Row.FindControl("HFO6AD"), HiddenField).Value
Dim OfficialsAccepted As Label = DirectCast(Row.FindControl("OfficialsAcceptedlbl"), Label)
Dim OfficialsNeeded As Label = DirectCast(Row.FindControl("OfficialsNeededlbl"), Label)
Dim RowID As String = DirectCast(Row.FindControl("IDlbl"), HyperLink).Text
Dim Cmd As SqlCommand
Dim dr As SqlDataReader
con.Open()
Cmd = New SqlCommand("Select OfficialsNeeded From Schedule WHERE ID ='" + RowID + "'", con)
dr = Cmd.ExecuteReader
dr.Read()
OfficialsNeeded.Text = dr(0).ToString
con.Close()
'Counting number of offiicials that have accepted
Dim N As Integer = 0
If HFO1AD = "Accept" Then
N = N + 1
End If
If HFO2AD = "Accept" Then
N = N + 1
End If
If HFO3AD = "Accept" Then
N = N + 1
End If
If HFO4AD = "Accept" Then
N = N + 1
End If
If HFO5AD = "Accept" Then
N = N + 1
End If
If HFO6AD = "Accept" Then
N = N + 1
End If
OfficialsAccepted.Text = N.ToString
Next
End Sub
From what I have read the way you are to do this is like the following but I get a null reference exception (Can't find the control)
Dim HFO1AD As String = DirectCast(e.Row.FindControl("HFO1AD"), HiddenField).Value
What am I doing wrong?
I figured it out.
I added the following if statement before my Dim statement and changed all my Dim statements back to look like this:
If e.Row.RowType = DataControlRowType.DataRow Then
Dim HFO2AD As String = DirectCast(e.Row.FindControl("HFO2AD"), HiddenField).Value

Open XLS File in a new window

I have simple Question and I would love to if someone can show me how to do it correctly,
I have a function that retrieving data
From the DB and I want to by click on button to export all the data to excel File
the thing is the file been saved on my C:\ drive and I want to open the file in a new window
or making saveFileDialog how can I do this?
Private Sub DatatableToExcel(ByVal dtTemp As DataTable)
Dim _excel As New Microsoft.Office.Interop.Excel.Application
Dim wBook As Microsoft.Office.Interop.Excel.Workbook
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
wBook = _excel.Workbooks.Add()
wSheet = wBook.ActiveSheet()
Dim dt As System.Data.DataTable = dtTemp
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
_excel.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
_excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
wSheet.Columns.AutoFit()
Dim strFileName As String = "C:\Testing.xlsx"
If System.IO.File.Exists(strFileName) Then
System.IO.File.Delete(strFileName)
End If
wBook.SaveAs(strFileName)
wBook.Close()
_excel.Quit()
End Sub
Process.Start with you're Excel file name as parameter.

changing the way of coding so that MS Excel is not to be needed to installed on server in asp.net

I have started to deveop a website using asp.net.
I need to fetch some data from excel to display it to the client.
I am hosting my site on somee.com so that I can freely host it.
But on the server of somee.com Excel is not installed.
I have written some code for my website to display the data from from excel.
Dim xlApp As New Microsoft.Office.Interop.Excel.Application()
Dim xlWorkbook As Microsoft.Office.Interop.Excel.Workbook = xlApp.Workbooks.Open(FileUploadPath & sender.text)
Dim xlWorksheet As Microsoft.Office.Interop.Excel._Worksheet = xlWorkbook.Sheets(SheetName)
Dim xlRange As Microsoft.Office.Interop.Excel.Range = xlWorksheet.UsedRange
Dim rowCount As Integer = xlRange.Rows.Count
Dim colCount As Integer = xlRange.Columns.Count
Dim tbl As New DataTable()
For i As Integer = 1 To rowCount
tbl.Rows.Add()
Next
For i As Integer = 1 To colCount
tbl.Columns.Add()
Next
If rowCount > 1 Or colCount > 1 Then
For i As Integer = 1 To rowCount
For j As Integer = 1 To colCount
tbl.Rows(i - 1)(j - 1) = xlRange.Value2(i, j)
Next j
Next i
End If
gvReadFiles.AutoGenerateColumns = True
gvReadFiles.DataSource = tbl
gvReadFiles.DataBind()
xlApp.ActiveWorkbook.Close(False, Session(FileUploadPath & sender.text))
xlApp.Quit()
xlWorkbook = Nothing
xlApp = Nothing
Now I need to have some changes in code so it is not excel dependent.
Can you help me?
I solved it using google for more than 2 hours.
Here is the code
Dim objConn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Try
Dim connString As String = ""
If Extension = "xls" Or Extension = ".xls" Then
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FileUploadPath & sender.text & ";Extended Properties=" + Convert.ToChar(34).ToString() + "Excel 8.0;HDR=No;IMEX=1" + Convert.ToChar(34).ToString() + ""
ElseIf Extension = "xlsx" Or Extension = ".xlsx" Then
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & FileUploadPath & sender.text & ";Extended Properties=" + Convert.ToChar(34).ToString() + "Excel 12.0;HDR=No;IMEX=1" + Convert.ToChar(34).ToString() + ""
End If
objConn = New OleDbConnection(connString)
objConn.Open()
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim firstSheetName As String = "Sheet1"
If Not dt Is Nothing Then
Dim excelSheets As [String]() = New [String](dt.Rows.Count - 1) {}
' Add the sheet name to the string array.
For Each row As DataRow In dt.Rows
firstSheetName = row("TABLE_NAME").ToString().Substring(0, row("TABLE_NAME").ToString.Length - 1)
Exit For
Next
End If
Return firstSheetName
Catch ex As Exception
Return "Sheet1"
Finally
If objConn IsNot Nothing Then
objConn.Close()
objConn.Dispose()
End If
If dt IsNot Nothing Then
dt.Dispose()
End If
End Try

ASP.net placing database model numbers into an array

Hey all i am trying to figure out how to add some of my model numbers from my database to am array while looping.
This is my code:
objCmd = New MySqlCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
If dtReader.HasRows() Then
grdViewItems.DataSource = dtReader
grdViewItems.DataBind()
Dim arrayOfItems As String() = New String() {}
While dtReader.Read()
arrayOfItems(intX) = dtReader.GetString("model_number")
'arrayItems(intX) = dtReader.GetString("model_number")
intX += 1
End While
'Session.Add("arrayOfItems", arrayItems)
Session("arrayOfItems") = arrayOfItems
dtReader.Close()
dtReader = Nothing
objConn.Close()
objConn = Nothing
End If
Problem being that it never populates the array with the values (although the values are present in the gridview because it skips the reading of the values in the while loop.
What am i doing incorrectly here?
Complete code
Dim intX As Integer = 0
objConn = New MySqlConnection(product.strConnString)
objConn.Open()
strSQL = "SELECT prod.id, PP.model_number, description, price, price_new, price_direct, price_builder " & _
"FROM product as prod " & _
"INNER JOIN product_price as PP ON PP.product_id = prod.type " & _
"WHERE prod.id = " & pageID & ";"
Try
objCmd = New MySqlCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
If dtReader.HasRows() Then
grdViewItems.DataSource = dtReader
grdViewItems.DataBind()
Dim arrayOfItems As New List(Of String)()
For Each row As GridViewRow In grdViewItems.Rows
arrayOfItems(intX) = row.Cells(0).Text.ToString
intX = intX + 1
Next
MsgBox(arrayOfItems(0))
'Session.Add("arrayOfItems", arrayItems)
Session("arrayOfItems") = arrayOfItems
dtReader.Close()
dtReader = Nothing
objConn.Close()
objConn = Nothing
End If
Catch ex As Exception
MsgBox("LoadProductItems: " & ex.Message)
End Try
Instead of array, I would recommend using List of int or string
It looks like the problem is in your loop. Replace the following code
Do While dtReader.Read
arrayOfItems(intX) = dtReader.GetString("model_number")
intX += 1
Loop
'with this code
While dtReader.Read()
arrayOfItems(intX) = dtReader.GetString("model_number")
intX += 1
End While
Updated Answer:
When you assign data to gridview then also save the data in a datatable like this
Dim dt As DataTable = New DataTable
dt = dtReader
`Then get the data from the table
Dim i As Integer = 0
Do While (i < dt.Rows.Count)
dt.Rows(i)("COlumnName").ToString
i = (i + 1)
Loop
Again Updated Answer:
Read the data from the gridview
For Each row As GridViewRow In grdViewItems.Rows
arrayOfItems(intX) = row.Cells(0).Text.ToString ` in cell specify the index of the model_number column
intX = intX + 1
Next

bulk copy duplicating each row when it is added to database

Why is my bulk copy duplicating each row, so in my database table the row shows twice.
Label1.Visible = True
Dim tourid As New List(Of String)
tourid.Add(TextBox1.Text)
Dim tasktype As New List(Of String)
Dim tourname1 As New List(Of String)
Dim tasknamelist As New List(Of String)
Dim dboxdates As New List(Of String)
Dim dates As New List(Of String)
Dim firstdates As New List(Of String)
Dim agent As New List(Of String)
Dim desc As New List(Of String)
Dim checkitem As ListItem
Dim departuredate As Date
For Each checkitem In dboxes.Items
If checkitem.Selected Then
departuredate = checkitem.Text
dboxdates.Add(departuredate)
For Each row As GridViewRow In GridView1.Rows
' Selects the text from the TextBox
Dim checkboxstatus As CheckBox = CType(row.FindControl("tasknamebox"), CheckBox)
If checkboxstatus.Checked = True Then
tasknamelist.Add(checkboxstatus.Text)
Dim dates1 As TextBox = CType(row.FindControl("tdays"), TextBox)
Dim gracep As TextBox = CType(row.FindControl("tgrace"), TextBox)
Dim aftersubtraction As DateTime
Dim fromatafter As DateTime
aftersubtraction = departuredate.AddDays(-dates1.Text)
fromatafter = aftersubtraction.AddDays(-gracep.Text)
firstdates.Add(fromatafter.ToString("MM/dd/yyyy"))
While fromatafter.DayOfWeek = DayOfWeek.Saturday OrElse fromatafter.DayOfWeek = DayOfWeek.Sunday
fromatafter = fromatafter.AddDays(-2)
End While
dates.Add(fromatafter.ToString("MM/dd/yyyy"))
Dim txtdesc2 As TextBox = CType(row.FindControl("txtdesc"), TextBox)
desc.Add(txtdesc2.Text)
Dim tasktype1 As Label = CType(row.FindControl("tasktype"), Label)
Dim agentdlist As DropDownList = CType(row.FindControl("agentdlist"), DropDownList)
tasktype.Add(tasktype1.Text)
agent.Add(agentdlist.text)
Dim tourname As String
tourname = tname.Text
Dim sChars As String = " "
tourname1.Add(tourname.TrimEnd(sChars))
End If
Next
End If
If tasknamelist.Count > dboxdates.Count Then
Do
dboxdates.Add(checkitem.Text)
Loop Until tasknamelist.Count = dboxdates.Count
End If
If tasknamelist.Count > tourid.Count Then
Do
tourid.Add(TextBox1.Text)
Loop Until tasknamelist.Count = tourid.Count
End If
Next
table.clear()
For i As Integer = 0 To ((dates.Count) - 1)
Dim row = table.NewRow()
row("Tour") = tourid(i)
row("TourName") = tourname1(i)
row("Task") = tasknamelist(i)
row("Departure") = dboxdates(i)
row("Due Date") = dates(i)
row("Task Type") = tasktype(i)
row("Agent Name") = agent(i)
row("Completed") = "NO"
row("Description") = desc(i)
row("Orig Due") = firstdates(i)
table.Rows.Add(row)
Next
toptable.Visible = False
bottom.Visible = True
GridView2.DataSource = table
GridView2.DataBind()
Using bcp As SqlBulkCopy = New SqlBulkCopy(SqlDataSource2.ConnectionString)
bcp.ColumnMappings.Add(0, 1)
bcp.ColumnMappings.Add(1, 2)
bcp.ColumnMappings.Add(2, 3)
bcp.ColumnMappings.Add(3, 4)
bcp.ColumnMappings.Add(4, 7)
bcp.ColumnMappings.Add(5, 5)
bcp.ColumnMappings.Add(6, 10)
bcp.ColumnMappings.Add(7, 13)
bcp.ColumnMappings.Add(8, 6)
bcp.DestinationTableName = "dbo.stagingtasks"
bcp.WriteToServer(table)
End Using
Your doing a table.Rows.Add(row) and a New SqlBulkCopy()
They seem to be the same?

Resources