DataSet not defined? - asp.net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim AppName As String = Session("App_Name").ToString()
Dim username As String = Session("username").ToString()
Dim password As String = Session("password").ToString()
Dim ds As DataSet = GContactsImport.GetGmailContacts(AppName, username, password)
GridView1.DataSource = ds
GridView1.DataBind()
End Sub
how do i fix it??
This is my class file
Imports Microsoft.VisualBasic
Imports Google.GData.Contacts
Imports Google.GData.Client
Imports Google.GData.Extensions
Imports Google.Contacts
Public Class Google
Public Shared Function GetGmailContacts(ByVal AppName As String, ByVal Uname As String, ByVal UPassword As String) As DataSet
Dim ds As New DataSet()
Dim dt As New DataTable()
Dim C2 As New DataColumn()
C2.DataType = Type.GetType
C2.ColumnName = "EmailID"
dt.Columns.Add(C2)
Dim rs As New RequestSettings(AppName, Uname, UPassword)
rs.AutoPaging = True
Dim cr As New ContactsRequest(rs)
Dim f As Feed(Of Contact) = cr.GetContacts()
For Each t As Contact In f.Entries
For Each email As EMail In t.Emails
Dim dr1 As DataRow = dt.NewRow()
dr1("EmailID") = email.Address.ToString()
dt.Rows.Add(dr1)
Next
Next
ds.Tables.Add(dt)
Return ds
End Function
End Class

Verify that DataSet is in scope (you may need to add an Import statement) or, alternatively, fully qualify the DataSet references in your code by replacing Dim ds As DataSet with Dim ds As System.Data.DataSet.

You might need to reference the System.Data assembly from the GAC and Imports System.Data (at the top of your file) in order to bring the DataSet class into scope.

Related

ASP.NET delete specific rows from gridview by checkbox

i need help with following code.its works well..but when page is loading it show all data from database and user can choose from them whichone rows he want to delete..
i want to use some kind of filter.
i mean.when page is loading,,its empty..i just input text in textbox and then click search button and all rows that contains specific text from textbox are diplayed..now i choose that rows i want to delete and mark them by checkbox to delete.
in easy words...i want to choose from specific rows that containts textbox text and mark them to delete...not from all rows ...
thank you all for any help
that my code
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Collections
Imports System.Text
Partial Public Class VB
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If IsPostBack Then
GetData()
End If
BindGrid()
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager _
.ConnectionStrings("conString").ConnectionString()
Dim query As String = "select * from TestCustomers"
Dim con As New SqlConnection(constr)
Dim sda As New SqlDataAdapter(query, con)
Dim dt As New DataTable()
sda.Fill(dt)
gvAll.DataSource = dt
gvAll.DataBind()
End Sub
Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
gvAll.PageIndex = e.NewPageIndex
gvAll.DataBind()
SetData()
End Sub
Private Sub GetData()
Dim arr As ArrayList
If ViewState("SelectedRecords") IsNot Nothing Then
arr = DirectCast(ViewState("SelectedRecords"), ArrayList)
Else
arr = New ArrayList()
End If
Dim chkAll As CheckBox = DirectCast(gvAll.HeaderRow _
.Cells(0).FindControl("chkAll"), CheckBox)
For i As Integer = 0 To gvAll.Rows.Count - 1
If chkAll.Checked Then
If Not arr.Contains(gvAll.DataKeys(i).Value) Then
arr.Add(gvAll.DataKeys(i).Value)
End If
Else
Dim chk As CheckBox = DirectCast(gvAll.Rows(i).Cells(0) _
.FindControl("chk"), CheckBox)
If chk.Checked Then
If Not arr.Contains(gvAll.DataKeys(i).Value) Then
arr.Add(gvAll.DataKeys(i).Value)
End If
Else
If arr.Contains(gvAll.DataKeys(i).Value) Then
arr.Remove(gvAll.DataKeys(i).Value)
End If
End If
End If
Next
ViewState("SelectedRecords") = arr
End Sub
Private Sub SetData()
Dim currentCount As Integer = 0
Dim chkAll As CheckBox = DirectCast(gvAll.HeaderRow _
.Cells(0).FindControl("chkAll"), CheckBox)
chkAll.Checked = True
Dim arr As ArrayList = DirectCast(ViewState("SelectedRecords") _
, ArrayList)
For i As Integer = 0 To gvAll.Rows.Count - 1
Dim chk As CheckBox = DirectCast(gvAll.Rows(i).Cells(0) _
.FindControl("chk"), CheckBox)
If chk IsNot Nothing Then
chk.Checked = arr.Contains(gvAll.DataKeys(i).Value)
If Not chk.Checked Then
chkAll.Checked = False
Else
currentCount += 1
End If
End If
Next
hfCount.Value = (arr.Count - currentCount).ToString()
End Sub
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim count As Integer = 0
SetData()
gvAll.AllowPaging = False
gvAll.DataBind()
Dim arr As ArrayList = DirectCast(ViewState("SelectedRecords") _
, ArrayList)
count = arr.Count
For i As Integer = 0 To gvAll.Rows.Count - 1
If arr.Contains(gvAll.DataKeys(i).Value) Then
DeleteRecord(gvAll.DataKeys(i).Value.ToString())
arr.Remove(gvAll.DataKeys(i).Value)
End If
Next
ViewState("SelectedRecords") = arr
hfCount.Value = "0"
gvAll.AllowPaging = True
BindGrid()
ShowMessage(count)
End Sub
Private Sub DeleteRecord(ByVal CustomerID As String)
Dim constr As String = ConfigurationManager _
.ConnectionStrings("conString").ConnectionString
Dim query As String = "delete from TestCustomers where" & _
" CustomerID=#CustomerID"
Dim con As New SqlConnection(constr)
Dim cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("#CustomerID", CustomerID)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Sub
Private Sub ShowMessage(ByVal count As Integer)
Dim sb As New StringBuilder()
sb.Append("<script type = 'text/javascript'>")
sb.Append("alert('")
sb.Append(count.ToString())
sb.Append(" records deleted.');")
sb.Append("</script>")
ClientScript.RegisterStartupScript(Me.GetType(), _
"script", sb.ToString())
End Sub
End Class
You just have to modify your SQL query. It is selecting all fields without any where condition. Let's assume you have two fields A and B in which you want to search for the text. Then your query should change to
Select * from TestCustomers where A like '%"+TextBox1.Text+"%' or B like '%"+TextBox1.Text+"%'

What namespace do I need to import in code behind vb asp.net to get a session value

Here is my code, session is not working, what is missing?
regards
Imports System.Web
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
End Class
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("dbconnection").ConnectionString)
con.Open()
Dim cmd As New SqlCommand("select * from nfl where UserName =#username and Password=#password", con)
cmd.Parameters.AddWithValue("#username", txtUserName.Text)
cmd.Parameters.AddWithValue("#password", txtPWD.Text)
Session["password"] = txtPWD.Text;
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
da.Fill(dt)
If dt.Rows.Count > 0 Then
Response.Redirect("Details.aspx")
Else
ClientScript.RegisterStartupScript(Page.[GetType](), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>")
End If
End Sub
End Class
Your not using C#.
This:
Session["password"] = txtPWD.Text;
should be:
Session("password") = txtPWD.Text

How do I print to the default printer on my Laptop from a VB.NET app I deployed to a IIS 8 server?

I've developed a VB.Net App using Visual studio 2015 on my Laptop which will print a rdlc local report for each selected row from a Gridview control directly to my laptop's default printer (which is a network printer) using the Microsoft code for 'walkthrough: Printing a Local Report without Preview' (and runs successfully on my local IIS express). When I deploy this App to a virtual company windows 2012 server that has IIS8 running, it no longer sees the default printer on my laptop (and tries to use the default printer on the windows 2012 server). I've searched the web to no success. I assume it's possible because when I use the reportviewer control in other apps I've developed and deployed on the Windows 2012 server, it can see the list of printers from my local laptop. Any ideas?
Here's the relevant VB code I'm using now...
Imports System.Management
Imports System
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Text
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Printing
Imports System.Collections.Generic
Imports Microsoft.Reporting.WebForms
Partial Class _Default
Inherits System.Web.UI.Page
Implements IDisposable
Private m_currentPageIndex As Integer
Private m_streams As IList(Of Stream)
Public Shared ViewID As String
Public Shared UserID As String
Public Shared StampID As String
Public Shared GridViewQry As String
Public Shared OpenCntr As Integer = 0
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim sqlConnection2 As New SqlConnection("DataSource=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim cmd2 As New SqlCommand
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1))
Response.Cache.SetNoStore()
OpenCntr = OpenCntr + 1
ViewID = Request.QueryString("ViewID")
If ViewID = "" Then
Response.Redirect("http://AOXWEBAPP1.SCOTT.COM/login/login.aspx")
Else
UserID = Request.QueryString("UserID")
StampID = Request.QueryString("StampID")
End If
cmd2.CommandText = "UpDate Super_FinalChk SET Selected=1 WHERE Printed = 1"
cmd2.Connection = sqlConnection2
sqlConnection2.Open()
cmd2.ExecuteNonQuery()
sqlConnection2.Close()
If OpenCntr = 1 Then
GridViewQry = "SELECT [Printed], [Customer], [AssySN], [Dte], [AssyPartNbr], [Operator], [PrintDate] FROM [Super_FinalChk] ORDER BY [Dte]"
End If
Dim adapter As New SqlDataAdapter(GridViewQry, sqlConnection2)
Dim superfinalchk As New DataSet("SqlDataSource1")
adapter.Fill(superfinalchk, "Super_FinalChkVw")
If (superfinalchk.Tables.Count > 0) Then
PrintATRs.DataSource = superfinalchk
If Not IsPostBack Then
PrintATRs.DataBind()
End If
Else
TextBox1.Text = "Unable to Connect to Database"
End If
' TextBox1.Text = DefaultPrinterName()
End Sub
' Routine to provide to the report renderer, in order to
' save an image for each page of the report.
Private Function CreateStream(ByVal name As String, ByVal fileNameExtension As String, ByVal encoding As Encoding, ByVal mimeType As String, ByVal willSeek As Boolean) As Stream
Dim stream As Stream = New MemoryStream()
m_streams.Add(stream)
Return stream
End Function
' Export the given report as an EMF (Enhanced Metafile) file.
Private Sub Export(ByVal report As LocalReport)
Dim deviceInfo As String = "<DeviceInfo>" &
"<OutputFormat>EMF</OutputFormat>" &
"<PageWidth>8.5in</PageWidth>" &
"<PageHeight>11in</PageHeight>" &
"<MarginTop>0.25in</MarginTop>" &
"<MarginLeft>0.50in</MarginLeft>" &
"<MarginRight>0.50in</MarginRight>" &
"<MarginBottom>0.25in</MarginBottom>" &
"</DeviceInfo>"
Dim warnings As Warning()
m_streams = New List(Of Stream)()
report.Render("Image", deviceInfo, AddressOf CreateStream, warnings)
For Each stream As Stream In m_streams
stream.Position = 0
Next
End Sub
' Handler for PrintPageEvents
Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
Dim pageImage As New Metafile(m_streams(m_currentPageIndex))
' Adjust rectangular area with printer margins.
Dim adjustedRect As New Rectangle(ev.PageBounds.Left - CInt(ev.PageSettings.HardMarginX),
ev.PageBounds.Top - CInt(ev.PageSettings.HardMarginY),
ev.PageBounds.Width,
ev.PageBounds.Height)
' Draw a white background for the report
ev.Graphics.FillRectangle(Brushes.White, adjustedRect)
' Draw the report content
ev.Graphics.DrawImage(pageImage, adjustedRect)
' Prepare for the next page. Make sure we haven't hit the end.
m_currentPageIndex += 1
ev.HasMorePages = (m_currentPageIndex < m_streams.Count)
End Sub
Private Sub PrintRep()
If m_streams Is Nothing OrElse m_streams.Count = 0 Then
Throw New Exception("Error: no stream to print.")
End If
Dim printDoc As New PrintDocument()
If Not printDoc.PrinterSettings.IsValid Then
**
It FAILS HERE!!!!
**
Throw New Exception("Error: cannot find the printer.")
Else
AddHandler printDoc.PrintPage, AddressOf PrintPage
m_currentPageIndex = 0
printDoc.Print()
End If
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
If m_streams IsNot Nothing Then
For Each stream As Stream In m_streams
stream.Close()
Next
m_streams = Nothing
End If
End Sub
Private Function LoadSuperFinalChkVwData(AssySN As String) As DataTable
Dim sqlConnection1 As New SqlConnection("Data Source=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim querystring As String = "SELECT * FROM dbo.Super_FinalChkVw WHERE AssySN = '" & AssySN & "'"
Dim adapter As New SqlDataAdapter(querystring, sqlConnection1)
Dim superfinalchkvw As New DataSet("DataSet1")
adapter.Fill(superfinalchkvw, "Super_FinalChkVw")
Return superfinalchkvw.Tables(0)
End Function
Protected Sub Print_Click(sender As Object, e As EventArgs) Handles Print.Click
Dim report As New LocalReport()
Dim sqlConnection2 As New SqlConnection("Data Source=AOXWEBAPP1\SQLEXPRESS;Initial Catalog=ManufacturingApps;User ID=AppUser;Password=#ppus3r;ApplicationIntent=ReadWrite")
Dim cmd2 As New SqlCommand
Dim cudate As DateTime
Dim AssySN As String
Dim cntr As Integer = 0
Dim SelectCount As Integer = 0
cudate = DateTime.Now
cmd2.Parameters.AddWithValue("#cudate", cudate)
For Each row As GridViewRow In PrintATRs.Rows
cntr = cntr + 1
Dim cb As CheckBox = DirectCast(row.FindControl("checkbox3"), CheckBox)
AssySN = row.Cells(3).Text
If cb.Checked Then
SelectCount = SelectCount + 1
report.ReportPath = "..\..\Manufacture\Superiox\ATR.rdlc"
report.DataSources.Clear()
report.DataSources.Add(New ReportDataSource("DataSet1", LoadSuperFinalChkVwData(AssySN)))
Export(report)
PrintRep()
cmd2.CommandText = "UpDate Super_FinalChk SET Selected=0, Printed=1, PrintDate=#cudate WHERE AssySN = '" & AssySN & "';"
cmd2.Connection = sqlConnection2
sqlConnection2.Open()
cmd2.ExecuteNonQuery()
sqlConnection2.Close()
End If
Next
Dim adapter As New SqlDataAdapter(GridViewQry, sqlConnection2)
Dim superfinalchk As New DataSet("SqlDataSource1")
adapter.Fill(superfinalchk, "Super_FinalChkVw")
PrintATRs.DataSource = superfinalchk
PrintATRs.DataBind()
If SelectCount > 0 Then
TextBox1.Text = "Reports Have Been Printed!"
Else
TextBox1.Text = "Please Select Reports to Print!"
End If
End Sub

401 Unauthorized - Google Drive API

I'm working with the Google APIs for the first time and I'm having problems trying to download files with the File object "downloadUrl" property. I'm currently using the "Service Account" option with the associated service account email and P12 certificate.
However, the URL returned "https://doc-08-68-docs.googleusercontent.com/docs/securesc/bteg36c1tifegg79l2ov17og25612tet/gk7kn52ahe4d0to7d6hte9f0f2hv47e4/1434132000000/11750183130219432819/11750183130219432819/0BziIKv2_NWCxc3RhcnRlcl9maWxl?e=download&gd=true" returns a 401 - Unauthorized response.
Imports System.Collections.Generic
Imports System.Security.Cryptography.X509Certificates
Imports System.IO
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Services
Imports Google.Apis.Auth.OAuth2
Namespace Videos
Partial Class List
Inherits System.Web.UI.UserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Const serviceAccountEmail As String = "#developer.gserviceaccount.com"
Dim certificate = New X509Certificate2(
Server.MapPath("~/bin/key.p12"),
"notasecret",
X509KeyStorageFlags.MachineKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable
)
Dim credential = New ServiceAccountCredential(
New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
.Scopes = New String() {DriveService.Scope.Drive}
}.FromCertificate(certificate)
)
Dim service = New DriveService(
New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = "LexVid-VideoEncode/1.0"
}
)
UxFiles.DataSource = RetrieveAllFiles(service)
UxFiles.DataBind()
End Sub
Public Shared Function RetrieveAllFiles(service As DriveService) As List(Of Data.File)
Dim result = New List(Of Data.File)()
Dim request As FilesResource.ListRequest = service.Files.List()
Do
Try
Dim files As FileList = request.Execute()
result.AddRange(files.Items)
request.PageToken = files.NextPageToken
Catch e As Exception
request.PageToken = Nothing
End Try
Loop While (Not String.IsNullOrEmpty(request.PageToken))
Return result
End Function
Public Shared Function DownloadFile(ByVal service As DriveService, ByVal file As Data.File) As System.IO.Stream
If (Not String.IsNullOrEmpty(file.DownloadUrl)) Then
Try
Dim x = service.HttpClient.GetByteArrayAsync(file.DownloadUrl)
Dim result As [Byte]() = x.Result
Return New MemoryStream(result)
Catch e As Exception
Return Nothing
End Try
Else
Return Nothing
End If
End Function
Protected Sub UxFiles_ItemDataBound(ByVal sender As Object, ByVal e As ListViewItemEventArgs) Handles UxFiles.ItemDataBound
Dim dataItem = CType(e.Item.DataItem, Data.File)
Dim file = CType(e.Item.FindControl("UxFile"), HyperLink)
file.NavigateUrl = dataItem.DownloadUrl
file.Text = dataItem.Title
End Sub
End Class
End Namespace
I got this resolved through some trial and error. Although I'm building the links manually now, so the request token isn't even necessary anymore. However, I'm posting here in case anyone else is looking to resolve a similar issue.
Imports System.Collections.Generic
Imports System.Security.Cryptography.X509Certificates
Imports System.IO
Imports System.Threading
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Services
Imports Google.Apis.Auth.OAuth2
Namespace Videos
Partial Class List
Inherits System.Web.UI.UserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Const serviceAccountEmail As String = "#developer.gserviceaccount.com"
Dim certificate = New X509Certificate2(
Server.MapPath("~/bin/key.p12"),
"notasecret",
X509KeyStorageFlags.MachineKeySet Or X509KeyStorageFlags.PersistKeySet Or X509KeyStorageFlags.Exportable
)
Dim credential As ServiceAccountCredential = New ServiceAccountCredential(
New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
.Scopes = New String() {DriveService.Scope.Drive}
}.FromCertificate(certificate)
)
If (credential.RequestAccessTokenAsync(CancellationToken.None).Result) Then
Dim service = New DriveService(
New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = "LexVid-VideoEncode/1.0"
}
)
UxFiles.DataSource = RetrieveAllFiles(service)
UxFiles.DataBind()
End If
End Sub
Public Shared Function RetrieveAllFiles(service As DriveService) As List(Of Data.File)
Dim result = New List(Of Data.File)()
Dim request As FilesResource.ListRequest = service.Files.List()
Do
Try
Const folderID As String = "0B5RLR6VRZsR4fkE5QjVFajg2dzZOMXZLYkNZUVdGbEtNODF0XzVBVGdjMW9ISDF5OE9kM0E"
request.Q = String.Format("'{0}' in parents and trashed=false", folderID)
Dim files As FileList = request.Execute()
result.AddRange(files.Items)
request.PageToken = files.NextPageToken
Catch e As Exception
request.PageToken = Nothing
End Try
Loop While (Not String.IsNullOrEmpty(request.PageToken))
Return result
End Function
Protected Sub UxFiles_ItemDataBound(ByVal sender As Object, ByVal e As ListViewItemEventArgs) Handles UxFiles.ItemDataBound
Dim dataItem = CType(e.Item.DataItem, Data.File)
Const folderID As String = "0B5RLR6VRZsR4fkE5QjVFajg2dzZOMXZLYkNZUVdGbEtNODF0XzVBVGdjMW9ISDF5OE9kM0E"
Dim file = CType(e.Item.FindControl("UxFile"), HyperLink)
file.NavigateUrl = String.Format("http://googledrive.com/host/{0}/{1}", folderID, dataItem.Title)
' Large files prompt for virus scan; no bypass available.
' file.NavigateUrl = String.Format("https://drive.google.com/uc?export=download&id={0}", dataItem.Id)
file.Text = dataItem.Title
End Sub
End Class
End Namespace

Adding new object into ArrayList, currently it rewrites the last object

I am adding products to an ArrayList to display with a repeater
Protected Sub Add_Click(sender As Object, e As EventArgs) Handles Add.Click
Dim ProductID As Integer = ddProduct.SelectedValue
Dim Qty As Integer = QtyBox.Text
Dim TempProduct As OrderEntry = fillProduct(ProductID, Qty)
OrderList.Add(TempProduct)
Orders.DataSource = OrderList
Orders.DataBind()
End Sub
However, when I add a new object, it replaces the old one with a new, and I assume its because it references the old object, instead of creating a new one. Where do I create a new one?
Imports System.Data
Imports System.Data.SqlClient
Partial Class placeOrder
Inherits System.Web.UI.Page
Dim OrderList As New ArrayList
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack() Then
dataFill()
End If
End Sub
Private Sub dataFill()
fillProduct()
End Sub
Private Sub fillProduct()
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("class_readonly").ConnectionString)
'Here bad connection string is a problem
conn.Open()
'Dim cmd As SqlCommand = conn.CreateCommand()
Dim sqlCmd As New SqlCommand()
With sqlCmd
.Connection = conn
.CommandText = "SELECT distinct ProductID, Name FROM dbo.Product;"
End With
Dim objDataAdapter As New SqlDataAdapter()
Dim objDataSet As New DataSet()
objDataAdapter.SelectCommand = sqlCmd
objDataAdapter.Fill(objDataSet)
ddProduct.DataSource = objDataSet.Tables(0)
ddProduct.DataBind()
End Sub
Protected Sub Add_Click(sender As Object, e As EventArgs) Handles Add.Click
Dim ProductID As Integer = ddProduct.SelectedValue
Dim Qty As Integer = QtyBox.Text
Dim TempProduct As OrderEntry = fillProduct(ProductID, Qty)
OrderList.Add(TempProduct)
Orders.DataSource = OrderList
Orders.DataBind()
dataFill()
End Sub
Private Function fillProduct(ByVal ProductID As Integer, ByVal Qty As Integer) As OrderEntry
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("class_readonly").ConnectionString)
'Here bad connection string is a problem
conn.Open()
'Dim cmd As SqlCommand = conn.CreateCommand()
Dim sqlCmd As New SqlCommand()
With sqlCmd
.Connection = conn
.CommandText = "SELECT * FROM dbo.Product WHERE ProductID=#ProductID ;"
.Parameters.Add(New SqlParameter("#ProductID", SqlDbType.Int, 4)).Value = ProductID
End With
Dim objDataAdapter As New SqlDataAdapter()
Dim objDataSet As New DataSet()
objDataAdapter.SelectCommand = sqlCmd
objDataAdapter.Fill(objDataSet)
Dim dtRow As DataRow = objDataSet.Tables(0).Rows(0)
Dim Total_Cost As Decimal = Decimal.Multiply(Qty, dtRow("Wholesale_Price"))
Dim Total_Price As Decimal = Decimal.Multiply(Qty, dtRow("Retail_Price"))
Dim Profit As Decimal = Total_Price - Total_Cost
Dim productInfo As New OrderEntry(dtRow("ProductID"), Qty, Total_Cost, Total_Price, Profit, dtRow("Name"))
sqlCmd.Dispose()
conn.Dispose()
Return productInfo
End Function
End Class
As #OneFineDay points out, if each element of your array is going to be of the same type then use an object of type "List Of" instead of "ArrayList".
This is how your class should look. You are saving your list to a session variable in Add_Click. In Page_Load, you are retrieving this session variable, casting it to a List(Of OrderEntry) and assigning it back to your page level list variable. Also I have removed the unnecessary dataFill procedure. Make sure that you understand the concepts rather than just copying and pasting.
Imports System.Data
Imports System.Data.SqlClient
Partial Class placeOrder
Inherits System.Web.UI.Page
Private m_myOrderList As List(Of OrderEntry)
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack() Then fillProduct()
m_myOrderList = CType(Session("MyOrderList"), List(Of OrderEntry))
End Sub
Private Sub fillProduct()
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("class_readonly").ConnectionString)
'Here bad connection string is a problem
conn.Open()
'Dim cmd As SqlCommand = conn.CreateCommand()
Dim sqlCmd As New SqlCommand()
With sqlCmd
.Connection = conn
.CommandText = "SELECT distinct ProductID, Name FROM dbo.Product;"
End With
Dim objDataAdapter As New SqlDataAdapter()
Dim objDataSet As New DataSet()
objDataAdapter.SelectCommand = sqlCmd
objDataAdapter.Fill(objDataSet)
ddProduct.DataSource = objDataSet.Tables(0)
ddProduct.DataBind()
End Sub
Protected Sub Add_Click(sender As Object, e As EventArgs) Handles Add.Click
If IsNothing(m_myOrderList) = True Then m_myOrderList = New List(Of OrderEntry)
Dim ProductID As Integer = ddProduct.SelectedValue
Dim Qty As Integer = QtyBox.Text
Dim TempProduct As OrderEntry = fillProduct(ProductID, Qty)
m_myOrderList.Add(TempProduct)
Session("MyOrderList") = m_myOrderList
Orders.DataSource = m_myOrderList
Orders.DataBind()
End Sub
Private Function fillProduct(ByVal ProductID As Integer, ByVal Qty As Integer) As OrderEntry
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("class_readonly").ConnectionString)
'Here bad connection string is a problem
conn.Open()
'Dim cmd As SqlCommand = conn.CreateCommand()
Dim sqlCmd As New SqlCommand()
With sqlCmd
.Connection = conn
.CommandText = "SELECT * FROM dbo.Product WHERE ProductID=#ProductID ;"
.Parameters.Add(New SqlParameter("#ProductID", SqlDbType.Int, 4)).Value = ProductID
End With
Dim objDataAdapter As New SqlDataAdapter()
Dim objDataSet As New DataSet()
objDataAdapter.SelectCommand = sqlCmd
objDataAdapter.Fill(objDataSet)
Dim dtRow As DataRow = objDataSet.Tables(0).Rows(0)
Dim Total_Cost As Decimal = Decimal.Multiply(Qty, dtRow("Wholesale_Price"))
Dim Total_Price As Decimal = Decimal.Multiply(Qty, dtRow("Retail_Price"))
Dim Profit As Decimal = Total_Price - Total_Cost
Dim productInfo As New OrderEntry(dtRow("ProductID"), Qty, Total_Cost, Total_Price, Profit, dtRow("Name"))
sqlCmd.Dispose()
conn.Dispose()
Return productInfo
End Function
End Class
OK so it's an ASP.NET webpage. After you click on the button, it's posting the page back to the server. OrderList does not persist between calls and is reinitialised with each click. Try adding OrderList to a session variable as follows in your button click procedure :
OrderList.Add(TempProduct)
Session("OrderList") = OrderList
and in your page load event, insert:
OrderList = Session("OrderList")
Also your dataFill procedure is superfluous. Delete that procedure and replace calls to dataFill with fillProduct. It's not an error but it's untidy.

Resources