i have 2 class 1 is get ms access data and another class for sql acsess.
i want to pass acsess class function value to sql class and assign it to sql class varible.curruntly i can assign only 1 varible.
Public Class connectionclass
Dim provider As String = "provider=Microsoft.ACE.OLEDB.12.0;data source=|DataDirectory|"
Dim database As String = "serverdata.accdb"
Public connstring As String = provider & database
Public myconnection As New OleDbConnection(connstring)
Public Function data1()
Dim x As String
Dim y As String
Dim u As String
Dim p As String
Try
myconnection.Open()
Dim getdata As New OleDbCommand("select * from server", myconnection)
Dim reader As OleDbDataReader = getdata.ExecuteReader
While reader.Read
x = reader.Item("sname")
y = reader.Item("dbase")
u = reader.Item("username")
p = reader.Item("password")
Return (x)
End While
myconnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
End Class
2nd class
ublic Class datbaseconnect
Public obj1 As New connectionclass
Dim returnvalue As String
Dim X = obj1.data1
Dim y = ""
Dim u = ""
Dim p = ""
Public SQLCon As New SqlConnection With
{.ConnectionString =
"Server=" & x & ";
DataBase=" & y & ";
user ID=" & u & ";
password=" & p & ";
Trusted_Connection=false;
"}
End Class
Tuples are a quick and easy way to return multiple data values in a single variable without having to create a whole new class to hold the individual values.
Public Function data1() As Tuple(Of String, String, String, String)
Dim x As String
Dim y As String
Dim u As String
Dim p As String
Try
myconnection.Open()
Dim getdata As New OleDbCommand("select * from server", myconnection)
Dim reader As OleDbDataReader = getdata.ExecuteReader
While reader.Read
x = reader.Item("sname")
y = reader.Item("dbase")
u = reader.Item("username")
p = reader.Item("password")
Return New Tuple(Of String, String, String, String)(x, y, u, p)
End While
myconnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
When calling this function it will return data like:
Dim returnedData = data1()
Finally, you simply call the function like:
WorkWithData(returnedData)
I wasn't able to include your own second class as I didn't see a function in there.
Public Sub WorkWithData(incomingData As Tuple(Of String, String, String, String))
Debug.Print(incomingData.Item1)
Debug.Print(incomingData.Item2)
Debug.Print(incomingData.Item3)
Debug.Print(incomingData.Item4)
End Sub
Related
all. I am a new VB.NET beginner. I am facing the issue of how to pass the dynamic SQL parameter values from the dynamic textboxes to search the data. I had added control of dynamic textboxes and labels and would like to search the data on the database table based on the dynamic textboxes value inputted from the user. Currently, I can only able to search the data from 1 dynamic textbox value only.
I want all the values from the dynamic textboxes that the user had been entered can be retrieved, and search the data based on the SQL parameter variable name and value entered by the user.
Can someone give me some solutions on how to solve this problem? I had stuck on this problem for a few days. Thank you for all the help!
What I had tried:
Private Sub FilterData()
Dim count As Integer = 0
'filterdata for radiobutton
Try
For Each TextBox As TextBox In grp2.Controls.OfType(Of TextBox)()
For Each Label As Label In grp2.Controls.OfType(Of Label)()
Using connection As New SqlConnection("connectionString")
'user key in the SQL statement
sql = TextBox1.Text
Dim sql2 As String
sql2 = sql
Dim sp1 As String() = sql.Split(New String() {"where"}, StringSplitOptions.None)
sql = sp1(0) & " where " & Label.Text & " = #parameter or " & Label.Text & " =#parameter"
If (TextBox.Text <> "") Then
count += 1
For j As Integer = 0 To count - 1
Using cmd As New SqlCommand(sql, connection)
cmd.Parameters.AddWithValue("#parameter", TextBox.Text)
'cmd.Parameters.Add("#parameter", SqlDbType.NVarChar, 20).Value = TextBox.Text
connection.Open()
Dim dt As New DataTable()
Dim reader As SqlDataReader
reader = cmd.ExecuteReader()
dt.Load(reader)
DataGridView1.DataSource = dt
End Using
Next
Else
GetData()
End If
'cmd.Dispose()
connection.Close()
End Using
Next
Next
Catch ex As Exception
'MsgBox(ex.Message)
End Try
End Sub
Firstly, if you have a 1:1 correspondence between Labels and TextBoxes then you should not be using two nested For Each loops, because that is going to pair up each and every Label with each and every TextBox. What you should be doing is creating arrays and then using a single For loop to access the pairs of controls:
Dim labels = grp2.Controls.OfType(Of Label)().ToArray()
Dim textBoxes = grp2.Controls.OfType(Of TextBox)().ToArray()
For i = 0 To labels.getUpperBound(0)
Dim label = labels(i)
Dim textBox = textBoxes(i)
'...
Next
As for build the SQL and adding the parameters, I would tend to do it something like this:
Dim labels = grp2.Controls.OfType(Of Label)().ToArray()
Dim textBoxes = grp2.Controls.OfType(Of TextBox)().ToArray()
Dim criteria As New List(Of String)
Dim command As New SqlCommand
For i = 0 To labels.getUpperBound(0)
Dim label = labels(i)
Dim textBox = textBoxes(i)
Dim parameterName = "#" & label.Text.Replace(" ", "_")
criteria.Add($"[{label.Text}] = {parameterName}")
command.Parameters.AddWithValue(parameterName, textBox.Text)
Next
Dim sql = "SELECT * FROM MyTable"
If criteria.Any() Then
sql &= " WHERE " & String.Join(" OR ", criteria)
End If
command.CommandText = sql
I think that you should begin to separate UI and data logic here is an example of implementation:
First you have a table in database:
CREATE TABLE Customer (
Id INT IDENTITY (1, 1) PRIMARY KEY,
FirstName VARCHAR (255) NOT NULL,
LastName VARCHAR (255) NOT NULL,
Phone VARCHAR (25),
Email VARCHAR (255) NOT NULL,
Street VARCHAR (255),
City VARCHAR (50),
State VARCHAR (25),
ZipCode VARCHAR (5)
);
Then you create the underlying entity in VB. Net:
Public Class Customer
Public Property Id As Integer
Public Property FirstName As String
Public Property LastName As String
Public Property Phone As String
Public Property Email As String
Public Property Street As String
Public Property City As String
Public Property State As String
Public Property ZipCode As String
End Class
Data loader
Now you need a data access component that loads records to a list of this above entity here a nice implementation:
Imports System.Data.SqlClient
Public Class CustomerDataAccess
Public Property ConStr As String
Public Sub New(ByVal constr As String)
constr = constr
End Sub
Public Function GetCustomersByCriterias(constraints As Object) As List(Of Customer)
Dim query As String = "SELECT Id, FirstName, LastName, Phone, Email, Street, City, State, ZipCode
FROM [dbo].[Customer] "
Dim result = New List(Of Customer)()
Using con = New SqlConnection(ConStr)
Using cmd = con.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = query
'' here the magic to add dynamic criteria coming from constraints
cmd.ApplyConstraints(Of Customer)(constraints)
con.Open()
LoadCustomerData(cmd, result)
End Using
End Using
Return result
End Function
Private Sub LoadCustomerData(ByVal cmd As SqlCommand, ByVal result As List(Of Customer))
Using rdr = cmd.ExecuteReader()
Dim idIdx As Integer = rdr.GetOrdinal("Id")
Dim firstNameIdx As Integer = rdr.GetOrdinal("FirstName")
Dim lastNameIdx As Integer = rdr.GetOrdinal("LastName")
Dim phoneIdx As Integer = rdr.GetOrdinal("Phone")
Dim emailIdx As Integer = rdr.GetOrdinal("Email")
Dim streetIdx As Integer = rdr.GetOrdinal("Street")
Dim cityIdx As Integer = rdr.GetOrdinal("City")
Dim stateIdx As Integer = rdr.GetOrdinal("State")
Dim zipCodeIdx As Integer = rdr.GetOrdinal("ZipCode")
While rdr.Read()
Dim item = New Customer()
item.Id = rdr.GetValueOrDefault(Of Integer)(idIdx)
item.FirstName = rdr.GetValueOrDefault(Of String)(firstNameIdx)
item.LastName = rdr.GetValueOrDefault(Of String)(lastNameIdx)
item.Phone = rdr.GetValueOrDefault(Of String)(phoneIdx)
item.Email = rdr.GetValueOrDefault(Of String)(emailIdx)
item.Street = rdr.GetValueOrDefault(Of String)(streetIdx)
item.City = rdr.GetValueOrDefault(Of String)(cityIdx)
item.State = rdr.GetValueOrDefault(Of String)(stateIdx)
item.ZipCode = rdr.GetValueOrDefault(Of String)(zipCodeIdx)
result.Add(item)
End While
End Using
End Sub
End Class
Extensions methods
Below are extensions methods referenced above that do the magic you are looking for:
DataReader extensions to make it easy to read values from SalDataReader with Dbnull exfeptional case and casting
Module DataReaderExtenions
<Extension()>
Function GetValueOrDefault(Of T)(row As IDataRecord, fieldName As String) As T
Dim ordinal = row.GetOrdinal(fieldName)
Return row.GetValueOrDefault(Of T)(ordinal)
End Function
<Extension()>
Function GetValueOrDefault(Of T)(row As IDataRecord, ordinal As Integer) As T
Return (If(row.IsDBNull(ordinal), Nothing, row.GetValue(ordinal)))
End Function
<Extension()>
Function GetValueOrDefaultSqlite(Of T)(row As IDataRecord, fieldName As String) As T
Dim ordinal = row.GetOrdinal(fieldName)
Return row.GetValueOrDefault(Of T)(ordinal)
End Function
<Extension()>
Function GetValueOrDefaultSqlite(Of T)(row As IDataRecord, ordinal As Integer) As T
Return (If(row.IsDBNull(ordinal), Nothing, Convert.ChangeType(row.GetValue(ordinal), GetType(T))))
End Function
End Module
Command extensions that lets you extract criteria from an anonymous object values:
Imports System.Reflection
Imports System.Runtime.CompilerServices
Module CommandExtensions
<Extension()>
Function AddParameter(command As IDbCommand, name As String, value As Object) As IDataParameter
If command Is Nothing Then Throw New ArgumentNullException("command")
If name Is Nothing Then Throw New ArgumentNullException("name")
Dim p = command.CreateParameter()
p.ParameterName = name
p.Value = If(value, DBNull.Value)
command.Parameters.Add(p)
Return p
End Function
<Extension()>
Function ToDictionary(data As Object) As Dictionary(Of String, Object)
If TypeOf data Is String OrElse data.[GetType]().IsPrimitive Then Return New Dictionary(Of String, Object)()
Return (From [property] In data.[GetType]().GetProperties(BindingFlags.[Public] Or BindingFlags.Instance)
Where [property].CanRead
Select [property]).ToDictionary(Function([property]) [property].Name, Function([property]) [property].GetValue(data, Nothing))
End Function
<Extension()>
Sub ApplyConstraints(Of TEntity)(cmd As IDbCommand, constraints As Object)
If constraints Is Nothing Then Return
Dim dictionary = constraints.ToDictionary()
Dim whereClause = " WHERE "
For Each kvp In dictionary
Dim columnName = kvp.Key
Dim propertyName = kvp.Key
Dim prefix = "#"c
Dim value = kvp.Value
whereClause += $"{columnName} **like** {prefix}{propertyName} AND "
cmd.AddParameter(propertyName, value)
Next
If String.IsNullOrEmpty(whereClause) Then Return
cmd.CommandText += whereClause.Remove(whereClause.Length - 5, 5)
End Sub
End Module
Example:
After coded all these stuff now you can do the following:
Dim DataGridView1 As DataGridView = New DataGridView()
Dim ConStr As String = ConfigurationManager.ConnectionStrings("MyApp").ConnectionString
Dim dal As CustomerDataAccess = New CustomerDataAccess(ConStr)
Dim criterias = New With {.FirstName = "%James%", .LastName = "%Nadin%"}
DataGridView1.DataSource = dal.GetCustomersByCriterias(criterias)
Despite all this code you are still need to bind your textbox (after naming them correctly) to a SearchEntity and use this entity to provide criterias
I hope this material can help you tackle your issue and incite you to improve your architecture & dev skills
Im trying to call to an URL
And than i will get response into XML format and based what Response i will get it will create Tables successfully into database using Microsoft SMO (Server Management Objects) which Allowing me to create and generate databases and tables. but for some reason it coludnt insert any data to tables and they are NULL Screenshot
XML:
<ICECAT-interface xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://data.icecat.biz/xsd/files.index.xsd">
<files.index Generated="20200219011050">
<file path="export/freexml.int/EN/1424.xml" Product_ID="1424" Updated="20200218012414" Quality="ICECAT" Supplier_id="1" Prod_ID="C4811A" Catid="846" On_Market="1" Model_Name="11" Product_View="513730" HighPic="http://images.icecat.biz/img/gallery/1424_6912543175.jpg" HighPicSize="2478427" HighPicWidth="2598" HighPicHeight="3276" Date_Added="20051023000000" Limited="No" >
<M_Prod_ID Supplier_id="11" Supplier_name="Cisco">C4811A</M_Prod_ID>
<M_Prod_ID>Tempcomp3109</M_Prod_ID>
<Country_Markets>
<Country_Market Value="NL"/>
<Country_Market Value="BE"/>
<Country_Market Value="FR"/>
<Country_Market Value="UA"/>
<Country_Market Value="GB"/>
<Country_Market Value="DE"/>
<Country_Market Value="BG"/>
</Country_Markets>
</file>
</files.index>
</ICECAT-interface>
Module:
Class Module1
Public Shared Sub Main()
Dim url As String = "http://data.Icecat.biz/export/freexml/EN/daily.index.xml"
ProcessXMLFeedURL(url)
End Sub
Public Shared Function ProcessXMLFeedURL(MyURL As String) As Boolean
Dim OK As Boolean = False
Try
Dim rssReq As WebRequest = WebRequest.Create(MyURL)
Dim username As String = ""
Dim password As String = ""
Dim encoded As String = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password))
rssReq.Headers.Add("Authorization", "Basic " + encoded)
'//Get the WebResponse
Dim rep As WebResponse = rssReq.GetResponse()
'//Read the Response in a XMLTextReader
Dim xtr As XmlTextReader = New XmlTextReader(rep.GetResponseStream())
'// Set up the connection to the SQL server
Dim MyConnectionString As String = "Data Source=......"
Dim Connection As SqlConnection = New SqlConnection(MyConnectionString)
Dim MyServer As Server = New Server(New ServerConnection(Connection))
Dim db As Database = New Database(MyServer, "xxxxx")
db.Create()
'//Create a new DataSet
Dim ds As DataSet = New DataSet()
'//Read the Response into the DataSet
ds.ReadXml(xtr)
'// Parse tables
For i As Integer = 0 To ds.Tables.Count - 1
Dim Mytable As Table
Dim MyTableName As String = ds.Tables(i).TableName
If Not HaveTable(MyConnectionString, MyTableName) Then
'// Create the table
Try
Mytable = New Table(db, MyTableName)
Catch ex As Exception
Dim ii As Integer = 0
End Try
'// Create the columns
Dim Mycolumn As Column = New Column()
For Each dc As DataColumn In ds.Tables(i).Columns
Mycolumn = New Column(Mytable, dc.ColumnName)
Mycolumn.DataType = getdatatype(dc.DataType.ToString)
Mytable.Columns.Add(Mycolumn)
Next
Mytable.Create()
Dim PrimaryKeys() As DataColumn = ds.Tables(i).PrimaryKey
Dim PrimaryKey As DataColumn
For Each PrimaryKey In PrimaryKeys
Dim Myindex As Index = New Index(Mytable, PrimaryKey.ColumnName)
Myindex.IndexKeyType = IndexKeyType.DriPrimaryKey
Myindex.IndexedColumns.Add(New IndexedColumn(Myindex, PrimaryKey.ColumnName))
Mytable.Indexes.Add(Myindex)
Next
End If
Using MyConnection As SqlConnection = New SqlConnection(MyConnectionString)
MyConnection.Open()
Using bulkcopy As SqlBulkCopy = New SqlBulkCopy(MyConnection)
bulkcopy.DestinationTableName = "[" & MyTableName & "]"
Try
bulkcopy.WriteToServer(ds.Tables(i))
Catch ex As Exception
Dim iw As Integer = 0
End Try
End Using
MyConnection.Close()
End Using
Next
Catch ex As Exception
Throw ex '// Do errorhanddling here
End Try
Return OK
End Function
Shared Function getdatatype(Mydatatype As String) As DataType
Dim dty As DataType = Nothing
Select Case Mydatatype
Case Is = "System.Decimal"
dty = DataType.Decimal(2, 18)
Case Is = "System.String"
dty = DataType.VarChar(500)
Case Is = "System.Int32"
dty = DataType.Int
End Select
Return dty
End Function
Shared Function HaveTable(MyConnectionString As String, TableName As String) As Boolean
Dim OK As Boolean = False
Try
Dim dbConn As New SqlConnection(MyConnectionString)
dbConn.Open()
Dim restrictions(3) As String
restrictions(2) = TableName
Dim dbTbl As DataTable = dbConn.GetSchema("Tables", restrictions)
If dbTbl.Rows.Count > 0 Then
OK = True
End If
dbTbl.Dispose()
dbConn.Close()
dbConn.Dispose()
Catch ex As Exception
Dim ss As Integer = 0
End Try
Return OK
End Function
End Class
Can anyone please help me!
I have 11 Access database files each having 20 items which needs to be stored in local variables as
RejRsnStn(i)(Reason) where i stands for station number 1 to 11 & Reason stands for Reason 1 to 20.
I am reading this data in following way:
Public Sub ReadReasonCodes()
'Station 1
For Reason = 1 To 20
DatafileStn = "E:\DATANetwork\DATAStation_1.accdb;Jet OLEDB:Database Password=xxxxxxxx"
Dim ConnstringStn As String = provider & DatafileStn
connstringwrkstn = ConnstringStn
myConnection.ConnectionString = ConnstringStn
myConnection.Open()
str = "SELECT * FROM Table_Config WHERE StationNo = 1"
cmd = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
RejRsnStn1(Reason) = If(IsDBNull(dr("RejectionReason" & Reason)), "NA", dr("RejectionReason" & Reason))
End While
myConnection.Close()
Next
'Station 2
For Reason = 1 To 20
DatafileStn = "E:\DATANetwork\DATAStation_2.accdb;Jet OLEDB:Database Password=xxxxxxxx"
Dim ConnstringStn As String = provider & DatafileStn
connstringwrkstn = ConnstringStn
myConnection.ConnectionString = ConnstringStn
myConnection.Open()
str = "SELECT * FROM Table_Config WHERE StationNo = 2"
cmd = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
RejRsnStn2(Reason) = If(IsDBNull(dr("RejectionReason" & Reason)), "NA", dr("RejectionReason" & Reason))
End While
myConnection.Close()
Next
End Sub
Can you please guide me with a concise method.
Thanks in advance.
Prashant.
I would do something like this:
First I would import System.Data.OleDb and then construct a class to contain all the codes:
Imports System.Data.OleDb
Public Class rCode
Dim _ReasonCode As String = ""
Public Property ReasonCode() As String
Get
Return _ReasonCode
End Get
Set(value As String)
_ReasonCode = value
End Set
End Property
End Class
Public Class RCodes
Public Property Station_1_Reasoncodes As New List(Of rCode)
Public Property Station_2_Reasoncodes As New List(Of rCode)
Public Property Station_3_Reasoncodes As New List(Of rCode)
Public Property Station_4_Reasoncodes As New List(Of rCode)
Public Property Station_5_Reasoncodes As New List(Of rCode)
Public Property Station_6_Reasoncodes As New List(Of rCode)
Public Property Station_7_Reasoncodes As New List(Of rCode)
Public Property Station_8_Reasoncodes As New List(Of rCode)
Public Property Station_9_Reasoncodes As New List(Of rCode)
Public Property Station_10_Reasoncodes As New List(Of rCode)
Public Property Station_11_Reasoncodes As New List(Of rCode)
End Class
Then I would initiate the class I just created:
public class form1
Public ReasonCodes As RCodes = New RCodes
Then I would make a subroutine to get the twenty codes from a database:
public class form1
Public ReasonCodes As RCodes = New RCodes
Public Sub GetReasonCodes(station As String)
Dim Provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Dim myConnection As New OleDbConnection
Dim DatafileStn As String = "E:\DATANetwork\DATAStation_" & station & ".accdb;Jet OLEDB:Database Password=xxxxxxxx"
Dim ConnstringStn As String = Provider & DatafileStn
myConnection.ConnectionString = ConnstringStn
myConnection.Open()
Dim cmd As New OleDbCommand("SELECT * FROM Table_Config WHERE StationNo = " & station, myConnection)
Dim dr As OleDbDataReader = cmd.ExecuteReader
Dim s As rCode = New rCode
Dim s2 As New List(Of rCode)
While dr.Read()
For Reason = 1 To 20
If IsDBNull(dr("RejectionReason" & CStr(Reason))) Then s.ReasonCode = "NA" Else s.ReasonCode = CStr(dr("RejectionReason" & CStr(Reason)))
s2.Add(s)
Next
End While
If Not dr.IsClosed Then dr.Close()
myConnection.Close()
dr = Nothing
myConnection = Nothing
Select Case station
Case "1"
ReasonCodes.Station_1_Reasoncodes = s2
Case "2"
ReasonCodes.Station_2_Reasoncodes = s2
Case "3"
ReasonCodes.Station_3_Reasoncodes = s2
Case "4"
ReasonCodes.Station_4_Reasoncodes = s2
Case "5"
ReasonCodes.Station_5_Reasoncodes = s2
Case "6"
ReasonCodes.Station_6_Reasoncodes = s2
Case "7"
ReasonCodes.Station_7_Reasoncodes = s2
Case "8"
ReasonCodes.Station_8_Reasoncodes = s2
Case "9"
ReasonCodes.Station_9_Reasoncodes = s2
Case "10"
ReasonCodes.Station_10_Reasoncodes = s2
Case "11"
ReasonCodes.Station_11_Reasoncodes = s2
End Select
End Sub
Then, I would make the initiator:
Public Sub ReadReasonCodes()
For i As Integer = 1 To 11
GetReasonCodes(CStr(i))
Next
End Sub
End Class
you can access your data from the class "ReasonCodes"
EXA:
Dim Stn6_code15 = ReasonCodes.Station_6_Reasoncodes(14).ReasonCode
'Note: since reasoncodes are stored in an Array, they are 0 based.
'So ReasonCodes.Station_6_Reasoncodes(14).ReasonCode =
'station 6, reason code 15.
Of course, I cannot test this, as I have no access DB files, but it should work, and if not it may require minor tweaks to obtain your goal.
Hope this helps you.
I am creating a routine that opens a SQL reader and loads a "Strapping Chart" (this will look up a predefined number that correlates to a specific volume of a vessel). On form load I want to populate the list these numbers will not change. (VolCnt , Volume). I am wanting to retrieve the correlated Volume based on the volumecount.
Here is what I have :
Public HltVolVals As List(Of HLTVolValChart)
Public Class HLTVolValChart
Public Property VCnt As Double
Public Property Volume As Double
Public Sub New(ByVal n_Vcnt As Double, ByVal n_Volume As Double)
Vcnt = n_Vcnt
Volume = n_Volume
End Sub
End Class
Public Sub PopulateHLTVolVals()
Dim sqlstr As String = "SELECT VCnt, Volume FROM Vol_Strap WHERE Vessel = 'HLT' ORDER BY Volume"
Dim CN As New SqlConnection
Dim Reader As SqlClient.SqlDataReader
Dim SQL As New SqlCommand
CN.ConnectionString = Connectionstr
CN.Open()
SQL.Connection = CN
SQL.CommandText = sqlstr
Reader = SQL.ExecuteReader
While Reader.Read
Dim Vol As Double = CDbl(Reader.GetValue(1))
Dim VCnt As Double = CDbl(Reader.GetValue(0))
Dim NewHLTVolValChartItem As List(Of HLTVolValChart) = New List(Of HLTVolValChart)
NewHLTVolValChartItem.Add(New HLTVolValChart(VCnt, Vol))
End While
Reader.Close()
CN.Close()
CN.Dispose()
End Sub
Public Function ListHLTVals(ByVal CurCnt As Double) As Double
Dim QVol = From _HLTVol In HltVolVals
Where _HLTVol.VCnt >= CurCnt
Select _HLTVol.Volume Take 1
Return QVol.First
End Function
The problem that I am having (I think) is while I loop through the records I am not creating multiple values within HLTVolValChart. However, I am not sure of the proper way to accomplish this.
Any help would be greatly appreciated.
Make NewHLTVolValChartItem a class variable. In your loop don't re-initialize the NewHLTVolValChartItem variable. That make a new List every iteration - just remove that part.
Private NewHLTVolValChartItem As New List(Of HLTVolValChart)
Public Sub PopulateHLTVolVals()
Dim sqlstr As String = "SELECT VCnt, Volume FROM Vol_Strap WHERE Vessel = 'HLT' ORDER BY Volume"
Dim CN As New SqlConnection
Dim Reader As SqlClient.SqlDataReader
Dim SQL As New SqlCommand
CN.ConnectionString = Connectionstr
CN.Open()
SQL.Connection = CN
SQL.CommandText = sqlstr
Reader = SQL.ExecuteReader
While Reader.Read
Dim Vol As Double = CDbl(Reader.GetValue(1))
Dim VCnt As Double = CDbl(Reader.GetValue(0))
NewHLTVolValChartItem.Add(New HLTVolValChart(VCnt, Vol))
End While
Reader.Close()
CN.Close()
CN.Dispose()
End Sub
I have two functions that check the same table, one right after the other. This setup seems inefficient. Is there a way to combine these?
getCustomerName(customerID)
getCustomerEmail(customerID)
'GET CUSTOMER NAME
Public Shared function getCustomerName(myArg) as String
Dim objConnection As New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("connectionString"))
Dim finalCustomerName as string
objConnection.Open()
Dim objCommand As New SqlCommand("SELECT customerName FROM customers WHERE customerID = '" + MyArg + "'", objConnection)
Dim objDataReader as SqlDataReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection)
While objDataReader.Read()
finalCustomerName = objDataReader("customerName")
End While
objConnection.Close()
Return finalCustomerName
End function
'GET CUSTOMER EMAIL
Public Shared function getCustomerEmail(myArg) as String
Dim objConnection As New SqlConnection(System.Configuration.ConfigurationSettings.AppSettings("connectionString"))
Dim finalCustomerEmail as string
objConnection.Open()
Dim objCommand As New SqlCommand("SELECT customerEmail FROM customers WHERE customerID = '" + MyArg + "'", objConnection)
Dim objDataReader as SqlDataReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection)
While objDataReader.Read()
finalCustomerEmail = objDataReader("customerEmail")
End While
objConnection.Close()
Return finalCustomerEmail
End function
Try this
New Customer class (you can add more properties that are related to customer and return them from function below):
Public Class Customer
Public Property CustomerName() As String
Get
Return m_CustomerName
End Get
Set
m_CustomerName = Value
End Set
End Property
Private m_CustomerName As String
Public Property CustomerEmail() As String
Get
Return m_CustomerEmail
End Get
Set
m_CustomerEmail = Value
End Set
End Property
Private m_CustomerEmail As String
End Class
And your function should be
// your function to get customer details
Public function getCustomer(myArg) as Customer
Dim custobj as New Customer()
Dim objCommand As New SqlCommand("SELECT customerEmail,CustomerName FROM customers WHERE customerID = #custid", objConnection)
objCommand.Parameters.AddWithValue("#custid",myArg) //use parameters to avoid sql injections
Dim objDataReader as SqlDataReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection)
While objDataReader.Read()
custobj.CustomerName = objDataReader("customerName")
custobj.CustomerEmail = objDataReader("customerEmail")
End While
objDataReader.Close()
objConnection.Close()
Return custObj
End function