Connecting To A Database Via Class Object Visual Basic 2010 - mysql

i have 2 classes
connect class
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class connect
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SqlCmd As MySqlCommand
Dim DR As MySqlDataReader
Public Function Con2Db() As Boolean
Try
'Prepare connection and query
dbCon = New MySqlConnection("Server=localhost; User Id = root; Pwd = 12345; Database = digitallibrary")
If dbCon.State = ConnectionState.Closed Then
dbCon.Open()
Return True
Else
dbCon.Close()
splash.Label1.Text = "Connection is Close"
Return False
End If
Catch ex As Exception
MsgBox("FAIL")
Return False
End Try
End Function
End Class
And query Class
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class query
Dim dbCon As MySqlConnection
Dim strQuery As String = ""
Dim SqlCmd As MySqlCommand
Dim DR As MySqlDataReader
Public Sub insert(ByVal ln As String, ByVal fn As String, ByVal mn As String, ByVal user As String, ByVal email As String, ByVal bdate As String, ByVal jdate As String, ByVal jtime As String, ByVal pwd As String)
Try
strQuery = "INSERT INTO user_tbl(user_ln,user_fn,user_mn,username,user_email,user_bdate, user_jdate, user_jtime)VALUES('" + ln + "','" + fn + "','" + mn + "','" + user + "','" + email + "','" + bdate + "','" + jdate + "','" + jtime + "' );" & _
"INSERT INTO login_tbl(username,password)VALUES('" + user + "','" + pwd + "')"
SqlCmd = New MySqlCommand(strQuery, dbCon)
SqlCmd.ExecuteNonQuery()
dbCon.Close()
Catch ex As Exception
MsgBox("Error " & ex.Message)
End Try
End Sub
End Class
Also A registration form
Public Class registration
Private Sub registration_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As New connect
If (con.Con2Db = True) Then
Label13.Text = "Connected To Database"
Else
Label13.Text = "Not Connected To Database"
End If
End Sub
Private Sub submit_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles submit_btn.Click
Dim ins As New query
Dim ln As String = ln_txt.Text
Dim fn As String = fn_txt.Text
Dim mn As String = mn_txt.Text
Dim user As String = user_txt.Text
Dim pwd As String = pwd_txt.Text
Dim cpwd As String = cpwd_txt.Text
Dim email As String = email_txt.Text
Dim year As String = year_cbx.Text
Dim month As String = month_cbx.Text
Dim day As String = day_cbx.Text
Dim bdate As String = year + "-" + month + "-" + day
Dim jdate As String = Format(Date.Now, "yyyy-MM-dd")
Dim jtime As String = Format(Date.Now, "HH:mm:ss")
ins.insert(ln, fn, mn, user, email, bdate, jdate, jtime, pwd)
End Sub
End Class
Everything is okay and it is saying on the label that the connection is successful but when I run the code it gives an error
Error Connection must be valid and open
I don't understand why the connection is said to be closed when the function is returning true...
If people are wondering why separate it to each classes it's because i'm trying to code cleanly(i hope and think) and i want to be more flexible in programming

The problem is that your 'connect' class has no relationship to your 'insert' function, meaning you are creating a new connection in each one. What you would have to do is create a Shared connection to your database that your connect class would manage, and your 'insert' function would use the existing connection.
There is nothing wrong with separating code into various sections, but you must know how to do it efficiently. I typically keep connection management and query execution in the same sections to avoid passing around extra objects. Here is what I would do:
Imports MySql.Data
Imports MySql.Data.MySqlClient
Public Class QueryManager
Dim dbCon As MySqlConnection
Public Sub ManageConnection(ByVal CloseConnection As Boolean)
Try
'Prepare connection and query'
dbCon = New MySqlConnection("Server=localhost; User Id = root; Pwd = 12345; Database = digitallibrary")
If CloseConnection = False Then
If dbCon.State = ConnectionState.Closed Then _
dbCon.Open()
Else
dbCon.Close()
End If
Catch ex As Exception
MsgBox("FAIL")
End Try
End Sub
Public Sub Insert(ByVal ln As String, ByVal fn As String, ByVal mn As String, ByVal user As String, ByVal email As String, ByVal bdate As String, ByVal jdate As String, ByVal jtime As String, ByVal pwd As String)
Try
ManageConnection(True) 'Open connection'
Dim strQuery As String = "INSERT INTO user_tbl(user_ln,user_fn,user_mn,username,user_email,user_bdate, user_jdate, user_jtime)" & _
"VALUES('" + ln + "','" + fn + "','" + mn + "','" + user + "','" + email + "','" + bdate + "','" + jdate + "','" + jtime + "' );" & _
"INSERT INTO login_tbl(username,password)VALUES('" + user + "','" + pwd + "')"
Dim SqlCmd As New MySqlCommand(strQuery, dbCon)
SqlCmd.ExecuteNonQuery()
ManageConnection(False) 'Close connection'
Catch ex As Exception
MsgBox("Error " & ex.Message)
End Try
End Sub
End Class
You would also no longer require the 'registration_Load' sub since the connection will only be opened while it's being used. If you wanted to create one shared connection and persist it through the entire application, you could adjust the functions to reflect your needs.

Related

mysql connection issues in parallel foreach loop

I have two classes. One class hold the database information while the other class processes information to and from the database; this class also accesses a server but that should not matter for this.
My problem is that when I try to use a foreach loop in parallel, the program randomly generates ssl connection error. The errors build up until the server blocks my IP address. If I keep the loop not in parallel, I have no errors. Unfortunately, I need the program to run faster. As a note, this is a standalone application so no need to worry about sql injection or anything.
How can I make this function in parallel?
Imports Newtonsoft.Json
' This class handles searching and extracting relevant data to the database
Public Class RiotDataExtractor
Private rda As New RiotDataAdapter
Private rm As New RemoteManager
Private summonerQueryCount As Integer = -5
Private strInsertQuery As String = ""
Private strUpdateQuery As String = ""
Public Sub New()
Try
dataExtraction()
Catch ex As Exception
Console.WriteLine(ex.Message + " in RiotDataExtractor/new.")
End Try
End Sub
' Gathers the list of summoners, |summonerQueryCount| at a time and send them to search their match history
Private Sub dataExtraction()
Try
Dim summoner_count As Integer = rm.returnDBQueryAsDataTable("SELECT COUNT(*) FROM summoner_data;").Rows(0).Item(0)
For i As Integer = (summoner_count - 1) To 0 Step summonerQueryCount
Dim dt As DataTable = rm.returnDBQueryAsDataTable("SELECT * FROM summoner_data limit " & (i + summonerQueryCount).ToString & ", " & (-summonerQueryCount).ToString() & ";")
If dt.Rows.Count = 0 Then
Exit For
End If
For j As Integer = 0 To dt.Rows.Count - 1
searchMatchHistoryForSummoner(dt.Rows(j).Item(3).ToString(), dt.Rows(j).Item(0).ToString())
Next
Next
Catch ex As Exception
Console.WriteLine(ex.Message + " in RiotDataExtractor/dataExtraction.")
End Try
End Sub
' Find the match history for a player from the database
Private Sub searchMatchHistoryForSummoner(ByVal strRegion As String, ByVal strAccountId As String)
Try
Dim convertedId As String = JsonConvert.DeserializeObject(Of LeagueSummonerData)(rda.convertID(strRegion, strAccountId)).accountId.ToString()
Dim matchHistory As LeagueMatchManager = JsonConvert.DeserializeObject(Of LeagueMatchManager)(rda.returnMatchHistoryForDataExtractor(strRegion, convertedId))
Parallel.ForEach(matchHistory.matches, Function(match As LeagueMatchList)
searchMatchData(match.gameId.ToString(), strRegion)
Return Nothing
End Function)
Catch ex As Exception
Console.WriteLine(ex.Message + " in RiotDataExtractor/searchMatchHistory.")
End Try
End Sub
' Search for match data from an ID
Private Sub searchMatchData(ByVal matchId As String, ByVal strRegion As String)
Try
Dim league_match As LeagueMatch = JsonConvert.DeserializeObject(Of LeagueMatch)(rda.returnLeagueMatch(matchId, strRegion))
'Parallel.ForEach(league_match.participantIdentities, Function(player As LeagueParticipantIdentity)
' searchPlayerInformation(player.player.summonerId.ToString(), strRegion)
' Return Nothing
' End Function)
For Each player In league_match.participantIdentities
searchPlayerInformation(player.player.summonerId.ToString(), strRegion)
Next
Catch ex As Exception
Console.WriteLine(ex.Message + " in RiotDataExtractor/searchMatchData.")
End Try
End Sub
' Uses summoner id from a match to gather all relevant information and insert into database
Private Sub searchPlayerInformation(ByVal summonerId As String, ByVal strRegion As String)
Debug.WriteLine(summonerId & "||" & strRegion)
If summonerId > 0 Then
Try
Dim summonerData As LeagueSummonerData = JsonConvert.DeserializeObject(Of LeagueSummonerData)(rda.returnLeagueSummoner(strRegion, summonerId))
Dim dt As DataTable = rm.returnDBQueryAsDataTable("SELECT * FROM summoner_data WHERE account_id = " + summonerData.id.ToString() + ";")
If dt.Rows.Count > 1 Then
rm.executeDBQuery("DELETE * FROM summoner_data WHERE account_id = ")
End If
If dt.Rows.Count = 1 Then
rm.executeDBQuery("UPDATE summoner_data SET summoner_name = '" + summonerData.name + "', summoner_level = " + summonerData.summonerLevel.ToString() + " WHERE account_id = " + summonerData.id.ToString() + " AND region = '" + strRegion + "';")
ElseIf (dt.Rows.Count = 0) Then
rm.executeDBQuery("INSERT INTO summoner_data (account_id, summoner_name, summoner_level, region) VALUES (" + summonerData.id.ToString() + ", '" + summonerData.name + "', " + summonerData.summonerLevel.ToString() + ", '" + strRegion + "');")
End If
Catch ex As Exception
Console.WriteLine(ex.Message + " in RiotDataExtractor/searchPlayerInformation.")
End Try
End If
End Sub
End Class
********************************************************
This is the class where I access the remote database.
Public Function returnDBQueryAsDataTable(ByVal strQuery As String) As DataTable
Dim dtLogin As DataTable = New DataTable()
Dim conn = New MySqlConnection(String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", summoner_spell, item_text, map_name, champ))
conn.Open()
Try
Using conn
Using cmd = New MySqlCommand(strQuery, conn)
Dim daLogin = New MySqlDataAdapter(cmd)
daLogin.Fill(dtLogin)
End Using
End Using
Catch ex As Exception
System.Diagnostics.Debug.WriteLine("Query failed: " + strQuery)
Finally
conn.Close()
End Try
Return dtLogin
End Function
Public Sub executeDBQuery(ByVal strQuery As String)
Try
Dim conn = New MySqlConnection(String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", summoner_spell, item_text, map_name, champ))
conn.Open()
Using conn
Using cmd = New MySqlCommand(strQuery, conn)
cmd.ExecuteNonQuery()
End Using
End Using
conn.Close()
Debug.WriteLine("Query succeeded: " + strQuery)
Catch ex As Exception
Debug.WriteLine("Query failed: " + strQuery + "//" + ex.Message)
End Try
End Sub
End Class

registration form encryption using vb.net and mysql

I have a registration form and I want to encrypt the password using whatever encryption is available, I'm using vb.net 2008 and MySQL as database, I searched through online and found some encrypting code but I have no idea how to connect it to my registration form. here is my registration code and the encryption code i found online (at the top part)
Imports MySql.Data.MySqlClient
Imports System.Security
Imports System.Security.Cryptography
Public Class user
Public Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return encrypted
Catch ex As Exception
End Try
End Function
Private Sub BCreateAcount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BCreateAcount.Click
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = "server = localhost;username= root;password= a;database= database"
Try
conn.Open()
Catch mali As MySqlException
MsgBox("connot establish connection")
End Try
Dim myCommand As New MySqlCommand
Dim myReader As MySqlDataReader
myCommand.Connection = conn
myCommand.CommandText = "insert into user values('" + txtUserName.Text + "','" + txtNewPassword.Text + "')"
Call calldaw()
If txtUserName.Text = "" Or txtNewPassword.Text = "" Or txtConfirmPassword.Text = "" Then
MsgBox("Please enter username and password", MsgBoxStyle.Information, "Inventory System")
ElseIf txtConfirmPassword.Text = txtNewPassword.Text Then
MsgBox("Account Created", MsgBoxStyle.Information, "Inventory System")
myReader = myCommand.ExecuteReader()
txtUserName.Text = ""
txtNewPassword.Text = ""
txtConfirmPassword.Text = ""
Else
MsgBox("Password did not match", MsgBoxStyle.Critical, "Inventory System")
txtConfirmPassword.Text = ""
txtNewPassword.Text = ""
txtUserName.Text = ""
End If
End Sub
Private Sub calldaw()
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = "server = localhost;username= root;password= a;database= database"
Try
conn.Open()
Catch mali As MySqlException
MsgBox("connot establish connection")
End Try
Dim myData As MySqlDataAdapter
Dim reason As String = " Create Account "
Dim tao As String = "admin"
myData = New MySqlDataAdapter
Dim sqlsql = "insert into daily_log values('" + tao + "','" + Date1.Text + "','" + reason + "','" + Time1.Text + "')"
Dim ssql = "Select * from user"
Dim myCommand As New MySqlCommand
myCommand.Connection = conn
myCommand.CommandText = sqlsql
Dim myReader As MySqlDataReader
myReader = myCommand.ExecuteReader
End Sub
Private Sub BBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BBack.Click
Me.Close()
End Sub
Private Sub user_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Date1.Text = Date.Today.Date
Dim Date2 As Date = Date1.Text
Date1.Text = Format(Date2, "yyyy-MM-dd")
Time1.Text = TimeOfDay
End Sub
End Class
any help will do, thanks.
You have to call the AES_Encrypt function before executing the INSERT statement in order to pass the encrypted password to database.
Dim myCommand As New MySqlCommand
Dim myReader As MySqlDataReader
myCommand.Connection = conn
myCommand.CommandText = "insert into user values('" + txtUserName.Text + "','" + AES_Encrypt(txtNewPassword.Text,txtNewPassword.Text) + "')"
Call calldaw()

import data from Excel to MySql using VB

Imports System.Data.Odbc
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports MySql.Data
Imports MySql.Data.MySqlClient
Imports ADODB
.
.
.
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Try
Dim conn As New OdbcConnection
Dim rset As New DataSet
Dim buff0 As String
Dim buff1 As String
Dim buff2 As String
Dim filePath As String = "C:\\Book3.xls"
conn.ConnectionString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DriverId=790;Dbq=" & filePath & ";" 'Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=d:\temp\test.xls;"
conn.Open()
rset.Open("select * from [Sheet1$]", conn, CursorTypeEnum.adOpenForwardOnly)
Do Until rset.EOF
buff0 = rset(0).Value
buff1 = rset(1).Value
buff2 = rset(2).Value
MySqlCmd = New MySqlCommand
MySqlCmd.Connection = Myconnect
MySqlCmd.CommandText = "INSERT INTO customers VALUES('" & buff0 & "','" & buff1 & "','" & buff2 & "')"
MySqlCmd.ExecuteNonQuery()
rset.MoveNext()
Loop
MsgBox("Import Successful!", MsgBoxStyle.Information, Title:="SOMS")
Catch ex As Exception
MsgBox("Import Unsuccessful!", MsgBoxStyle.Critical, Title:="SOMS")
End Try
End Sub
I am trying to import data from excel to mysql using this code got from web. But getting some errors. Give me suggestion where i am going wrong. I am very newbe for ADO,OLE. here i am using ODBC for reading data from excel and for insert I use mysql native driver. Another question is, Am i going in right direction or otherways possible?
Try this code and tell me :
Private Sub SimpleButton1_Click(sender As Object, e As EventArgs) Handles SimpleButton1.Click
Dim dialog As New OpenFileDialog()
dialog.Filter = "Excel files |*.xls;*.xlsx"
dialog.InitialDirectory = "C:\"
dialog.Title = "Select file for import"
If dialog.ShowDialog() = DialogResult.OK Then
Dim dt As DataTable
Dim buff0 As String
Dim buff1 As String
Dim buff2 As String
dt = ImportExceltoDatatable(dialog.FileName)
For i = 0 To dt.Rows.Count - 1
buff0 = dt.Rows(i)(0)
buff1 = dt.Rows(i)(1)
buff2 = dt.Rows(i)(2)
MySqlCmd = New MySqlCommand
MySqlCmd.Connection = Myconnect
MySqlCmd.CommandText = "INSERT INTO customers VALUES('" & buff0 & "','" & buff1 & "','" & buff2 & "')"
MySqlCmd.ExecuteNonQuery()
Next
End If
End Sub
Public Shared Function ImportExceltoDatatable(filepath As String) As DataTable
' string sqlquery= "Select * From [SheetName$] Where YourCondition";
Dim dt As New DataTable
Try
Dim ds As New DataSet()
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filepath & ";Extended Properties=""Excel 12.0;HDR=YES;"""
Dim con As New OleDbConnection(constring & "")
con.Open()
Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim sqlquery As String = String.Format("SELECT * FROM [{0}]", myTableName) ' "Select * From " & myTableName
Dim da As New OleDbDataAdapter(sqlquery, con)
da.Fill(ds)
dt = ds.Tables(0)
Return dt
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
Return dt
End Try
End Function

After adding to hosted mysql base how to read vbasic 2012

I'm working on simple project to figure out how databases work.
I created mysql base on my host and used this code to connect to it
Private mysql_host = "myhost"
Private mysql_user = "myuser"
Private mysql_pass = "mypw"
Private mysql_db = "mydb"
Private SQLConnect As String = "Server=" + mysql_host + ";" + "User Id=" + mysql_user + ";" + "Password=" + mysql_pass + ";" + "Database=" + mysql_db
Private SQLConnection As New MySqlConnection
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
sqlConnection.ConnectionString = SQLConnect
Try
If sqlConnection.State = ConnectionState.Closed Then
sqlConnection.Open()
MsgBox("Connected")
Else
sqlConnection.Close()
MsgBox("Not Connected")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
After that i used this code to add record into database.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim SQLStatement As String = "INSERT into tCodes(Code) VALUES ('" & TextBox1.Text & "')"
Dim cmd As New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
MsgBox("Added")
End Sub
On the other form i want to check if record exist in database. How to do that .
I tried with code
Dim SQLStatement As String = "SELECT * From tCodes WHERE Code '" & TextBox1.Text & "'")
For read . Me using this
Private host As String = "host" 'Host DB
Private user As String = "user" 'User DB
Private pass As String = "pass" 'Pass DB
Private base As String = "base" 'Base
Private conn As String = "Database=" & base & ";Data Source=" & host & ";User Id=" & _
user & ";Password=" & pass 'Connection
Private Connection As New MySqlConnection(conn) 'Connection
Private readData As MySqlDataReader 'Data Reader
Private adaptsData As New MySqlDataAdapter 'Data Adapter
Private command As New MySqlCommand 'command
Private ds As New DataSet 'DataSet
After
Public Function __select(Optinal table as String = "tCodes") As String
Try
Connection.Open()
Dim query As String = "SELECT * FROM " & table
command.CommandText = query
command.Connection = conexiune
adaptsData.SelectCommand = comanda
adaptsData.Fill(ds, tabla)
Dim newvalue As String = ds.Tables(tabla).Rows(0).Item(item)
ds.Dispose()
ds.Clear()
Connection.Close()
Return newvalue
Catch ex As Exception
ds.Dispose()
ds.Clear()
conexiune.Close()
msgbox(ex.message)
End Try
End Function
Dim conn As MySqlConnection
Dim sqlquery = "SELECT * FROM tCodes WHERE Code = '" + txtCode.Text + "'"
Dim myCommand As New MySqlCommand()
myCommand.Connection = conn
myCommand.CommandText = sqlquery
'start query
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader()
'see if user exists
If myData.HasRows = 0 Then
MsgBox("Kod je nevazeci")
conn.Close()
Else
MsgBox("Kod je vazeci")
End If
That was the solution of this problem

How to use http request query string property to filter where clause

I need to filter where clause in my GetProduct function using http request query string property. I have set up my filters in urls. (eg burgers.aspx?filter=burgers'). Burgers is the name of database table category(Where ProductCat = filter). I understand I need to pass parameter to interaction class because it does not handle requests. Please help.
Interaction class:
Public Class Interaction
Inherits System.Web.UI.Page
' New instance of the Sql command object
Private cmdSelect As New SqlCommand
' Instance of the Connection class
Private conIn As New Connection
Region "Menu functions and subs"
' Set up the SQL statement for finding a Product by ProductCat
Private Sub GetProduct(ByVal CatIn As String)
' SQL String
Dim strSelect As String
strSelect = "SELECT * "
strSelect &= " FROM Menu "
strSelect &= " WHERE ProductCat = "
strSelect &= "ORDER BY 'ProductCat'"
' Set up the connection to the datebase
cmdSelect.Connection = conIn.Connect
' Add the SQL string to the connection
cmdSelect.CommandText = strSelect
' Add the parameters to the connection
cmdSelect.Parameters.Add("filter", SqlDbType.NVarChar).Value = CatIn
End Sub
'Function to create list of rows and columns
Public Function ReadProduct(ByVal CatIn As String) As List(Of Dictionary(Of String, Object))
'Declare variable to hold list
Dim ReturnProducts As New List(Of Dictionary(Of String, Object))
Try
Call GetProduct(CatIn)
Dim dbr As SqlDataReader
' Execute the created SQL command from GetProduct and set to the SqlDataReader object
dbr = cmdSelect.ExecuteReader
'Get number of columns in current row
Dim FieldCount = dbr.FieldCount()
Dim ColumnList As New List(Of String)
'Loop through all columns and add to list
For i As Integer = 0 To FieldCount - 1
ColumnList.Add(dbr.GetName(i))
Next
While dbr.Read()
'Declare variable to hold list
Dim ReturnProduct As New Dictionary(Of String, Object)
'Loop through all rows and add to list
For i As Integer = 0 To FieldCount - 1
ReturnProduct.Add(ColumnList(i), dbr.GetValue(i).ToString())
Next
'Add to final list
ReturnProducts.Add(ReturnProduct)
End While
cmdSelect.Parameters.Clear()
'Close connection
dbr.Close()
Catch ex As SqlException
Dim strOut As String
strOut = ex.Message
Console.WriteLine(strOut)
End Try
' Return the Product object
Return ReturnProducts
End Function
Code Behind:
Partial Class Burger
Inherits System.Web.UI.Page
'String Used to build the necessary markup and product information
Dim str As String = ""
''Var used to interact with SQL database
Dim db As New Interaction
' New instance of the Sql command object
Private cmdSelect As New SqlCommand
' Instance of the Connection class
Private conIn As New Connection
Protected Sub printMenuBlock(ByVal productName As String)
'Set up variable storing the product and pull from databse
Dim product = db.ReadProduct(productName)
'Add necessary markup to str variable, with products information within
For i As Integer = 0 To product.Count - 1
str += "<div class='menuItem'>"
'str += " <img alt='Item Picture' class='itemPicture' src='" + product(i).ImagePath.Substring(3).Replace("\", "/") + "' />"
str += " <div class='itemInfo'>"
str += " <h1 class='itemName'>"
str += " " + product(i).Item("ProductName") + "</h1>"
'str += " <h3 class='itemDescription'>"
str += " " + product(i).Item("ProductDescription")
str += " <h1 class ='itemPrice'>"
str += " " + product(i).Item("ProductPrice") + "</h1>"
str += " "
str += " </div>"
str += " </div>"
Next
End Sub
''Uses
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Dim v = Request.QueryString("filter")
'Response.Write("filter is")
'Response.Write(v)
Dim value = Request.QueryString("filter")
'Get string from printMenuBlock method
printMenuBlock(str)
'Print the str variable in menuPlace div
menuPlace.InnerHtml = str
End Sub
End Class
I need a direction on how to pass the Request.QueryString("filter") to GetProduct function to filter by page according to ProductCategory. Thanks in advance.
Try something like this:
Dim filter = Request.QueryString("filter")
Dim sqlStr = "Select * From menu Where ProductCat = #filter Order By ProductCat"
cmdSelect.Parameters.Add("filter", SqlDbType.NVarChar).Value = filter