Reading multiple data from multiple databases in vb.Net - vb.net

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.

Related

Read from two tables information

How can i convert this code to read information from the two tables.
Private Sub GenerateDynamicUserControl()
FlowLayoutPanel1.Controls.Clear()
Dim dt As DataTable = New ClassBLL().GetItems()
If dt IsNot Nothing Then
If dt.Rows.Count > 0 Then
Dim listItems As ListItem() = New ListItem(dt.Rows.Count - 1) {}
For i As Integer = 0 To 1 - 1
For Each row As DataRow In dt.Rows
Dim listItem As New ListItem()
listItems(i) = listItem
'Dim ms As New MemoryStream(CType(row("userPic"), Byte()))
listItems(i).Width = FlowLayoutPanel1.Width - 30
listItems(i).Icon = orderPicFromString
listItems(i).Icon2 = orderPicFromString2
listItems(i).OrderFrom = row("orderfrom").ToString()
listItems(i).OrderTitle = orderTitleString
listItems(i).OrderReceiver = row("orderreceiver").ToString()
listItems(i).OrderTitle2 = orderTitleString2
'listItems(i).ButtonBackground = orderButtonBackString
listItems(i).ButtonText = row("orderstatus").ToString()
listItems(i).OrderDate = row("orderdate")
listItems(i).IDOrder = row("orderid").ToString()
If listItems(i).ButtonText = "Accepted" Then
listItems(i).ButtonBackground = Color.FromArgb(26, 168, 92)
ElseIf listItems(i).ButtonText = "Declined" Then
listItems(i).ButtonBackground = Color.FromArgb(246, 50, 90)
ElseIf listItems(i).ButtonText = "Proceed" Then
listItems(i).ButtonBackground = Color.FromArgb(255, 174, 33)
ElseIf listItems(i).ButtonText = "Waiting" Then
listItems(i).ButtonBackground = Color.FromArgb(53, 121, 255)
Else
listItems(i).ButtonBackground = Color.FromArgb(91, 146, 255)
End If
FlowLayoutPanel1.Controls.Add(listItems(i))
Next
Next
End If
End If
End Sub
So let me start with information about this that is in RED , i need to get this information from another table that is called "Profiles"
listItems(i).Icon = orderPicFromString
listItems(i).Icon2 = orderPicFromString2
listItems(i).OrderTitle = orderTitleString
listItems(i).OrderTitle2 = orderTitleString2
So this fields i need to read them from table "Profiles"
So next is as you see the code up calls Class GetItems:
Public Function GetItems() As DataTable
Try
Dim objdal As New ClassDAL()
Return objdal.ReadItemsTable()
Catch e As Exception
Dim result As DialogResult = MessageBox.Show(e.Message.ToString())
Return Nothing
End Try
End Function
Public Function ReadItemsTable() As DataTable
Using cons As New OleDbConnection(ServerStatus)
Using cmd As New OleDbCommand()
cmd.Connection = cons
cmd.CommandText = "SELECT * FROM OrdersAssigned ORDER BY ID ASC"
cons.Open()
Using sda As New OleDbDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function
So this is main function to display the results from row("name")
Then i try to create like this:
'Declare Strings for OrderDisplay
Public orderFromString As String
Public orderTitleString As String
Public orderReceiveString As String
Public orderTitleString2 As String
Public orderButtonBackString As Color
Public orderButtonTextString As String
Public orderDateString As Date
Public orderIDString As String
Public orderPicFromString As Image
Public orderPicFromString2 As Image
'Get Accounts Name
Public orderAccountFrom As String
Public orderAccountTo As String
Public Sub GetUserPictureFrom()
Using conn As New OleDbConnection(ServerStatus)
conn.Open()
Dim sql As String = "Select userPicture From Profiles where userAccount=#GetLogin"
Using cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#GetLogin", orderAccountFrom)
Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If imageData IsNot Nothing Then
Using stream As New MemoryStream(imageData)
Dim backgroundImage As Image = Image.FromStream(stream)
orderPicFromString = backgroundImage
End Using
End If
End Using
End Using
End Sub
Public Sub GetUserPictureTo()
Using conn As New OleDbConnection(ServerStatus)
conn.Open()
Dim sql As String = "Select userPicture From Profiles where userAccount=#GetLogin"
Using cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#GetLogin", orderAccountTo)
Dim imageData As Byte() = DirectCast(cmd.ExecuteScalar(), Byte())
If imageData IsNot Nothing Then
Using stream As New MemoryStream(imageData)
Dim backgroundImage As Image = Image.FromStream(stream)
orderPicFromString2 = backgroundImage
End Using
End If
End Using
End Using
End Sub
Public Sub GetOrdersDisplay()
Using cons As New OleDbConnection(ServerStatus)
Using cmd As New OleDbCommand()
cmd.Connection = cons
cmd.CommandText = "SELECT * FROM OrdersAssigned ORDER BY ID ASC"
cons.Open()
Using rdr As OleDbDataReader = cmd.ExecuteReader()
While rdr.Read()
orderAccountFrom = rdr("orderacc").ToString
orderAccountTo = rdr("orderreceiveracc").ToString
End While
End Using
cmd.CommandText = "Select userPosition From Profiles where userAccount = #GetUser"
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#GetUser", orderAccountFrom)
Using rds As OleDbDataReader = cmd.ExecuteReader()
While rds.Read()
orderTitleString = rds("userPosition").ToString
End While
End Using
cmd.CommandText = "Select userPosition From Profiles where userAccount = #ToUser"
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#ToUser", orderAccountTo).ToString()
Using rdx As OleDbDataReader = cmd.ExecuteReader()
While rdx.Read()
orderTitleString2 = rdx("userPosition").ToString
End While
End Using
End Using
End Using
GetUserPictureFrom()
GetUserPictureTo()
End Sub
What it needs to do is:
orderAccountFrom = rdr("orderacc").ToString
orderAccountTo = rdr("orderreceiveracc").ToString
will get the accounts from table OrdersAssigned and search with them in table Profiles to get results userPosition
What means this
userx in Profiles has userPosition = Boss
usery in Profiles has userPosition = Worker
i want to fetch this information.
The same goes for the pictures each user has his own picture.
How can i manage to fix this issue so to get correct data?
How can i combine all of this inside the function ReadItemsTable() it would be better to be in one place everything so
listItems(i).Icon = orderPicFromString
listItems(i).Icon2 = orderPicFromString2
listItems(i).OrderTitle = orderTitleString
listItems(i).OrderTitle2 = orderTitleString2
to work correct to get information
cmd.CommandText = "SELECT OrdersAssigned.*,
ProfilesFrom.userPosition AS UserPositionFrom,
ProfilesFrom.userPicture AS UserPictureFrom,
ProfilesTo.userPosition AS UserPositionTo,
ProfilesTo.userPicture AS UserPictureTo
FROM
(OrdersAssigned
LEFT OUTER JOIN Profiles AS ProfilesFrom ON OrdersAssigned.orderacc = ProfilesFrom.userAccount)
LEFT OUTER JOIN Profiles AS ProfilesTo ON OrdersAssigned.orderreceiveracc = ProfilesTo.userAccount
ORDER BY
OrdersAssigned.ID ASC;"

Pass multiple Value to class from function

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

asp.net vb Button.click insert to sql working at client but not working when move to server

This code is working a PC. I have filled grid view with the dataset, so I suppose I can read Excel.
However, the insert to sql part is not working when I copy the code to the server and I don't know why. It is not throwing any errors.
I removed the try catch lines but still, there are no errors.
I am adding new code block, I did a test and wrote a siple insert code like;
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim mysql_connection As New SqlConnection
mysql_connection.ConnectionString = "Data Source=SRV01;Initial Catalog=TR_Development;Persist Security Info=True;User ID=sa"
Dim command As String = "insert into gez_test (test) values ('c')"
Dim mysqlcommand As New SqlCommand
mysqlcommand.CommandType = CommandType.Text
mysqlcommand.CommandText = command
mysqlcommand.Connection = mysql_connection
If mysql_connection.State = ConnectionState.Closed Then mysql_connection.Open()
mysqlcommand.ExecuteNonQuery()
If mysql_connection.State = ConnectionState.Open Then mysql_connection.Close()
End Sub
And at server it is not inserting. What can be the problem any idea?
Orginal code
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim path_ As String = "\\exchange\COMPANY\web\" + FileUpload1.FileName
FileUpload1.PostedFile.SaveAs(path_)
Dim identifier As Boolean = False
Dim connStr As String = "provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + path_ + "';Extended Properties=Excel 12.0;"
Dim MyConnection As OleDbConnection
Dim ds As DataSet
Dim MyCommand As OleDbDataAdapter
MyConnection = New OleDbConnection(connStr)
MyConnection.Open()
Dim dtSheets As DataTable = MyConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
For Each sheet As String In listSheet
If sheet = "'BAS+Surcharges$'" Then
identifier = True
Exit For
End If
Next
If identifier = True Then
MyCommand = New OleDbDataAdapter("select * from [BAS+Surcharges$]", MyConnection)
ds = New System.Data.DataSet()
MyCommand.Fill(ds)
MyConnection.Close()
'**************SQL***************
Dim line, columns As Integer
line = ds.Tables(0).Rows.Count
columns = ds.Tables(0).Columns.Count
Label1.Text = line.ToString
ASPxTextBox1.Text = line.ToString
If line > 0 And columns = 16 Then
Dim command As String = "exec SP_INTRA_EXCEL_LINE_INSERT" _
+ " #line_isim, #nereden, #via, #nereye, #transit_sure, #baslangic_tarihi," _
+ "#e_kadar_gecerli, #kalem_kodu, #fiyatlandirma, #20DRY, #40DRY, #40HDRY," _
+ "#40HREF_NOR, #kayit_eden"
Dim mysql_connection As New SqlConnection
mysql_connection.ConnectionString = ConfigurationManager.ConnectionStrings("TR_DevelopmentConnectionString").ConnectionString
Dim mysqlcommand As New SqlCommand
mysqlcommand.CommandType = CommandType.Text
mysqlcommand.CommandText = command
mysqlcommand.Connection = mysql_connection
Dim line_isim, nereden, via, nereye, transit_sure, baslangic_tarihi, e_kadar_gecerli,
kalem_kodu, fiyatlandirma, _20DRY, _40DRY, _40HDRY,
_40HREF_NOR, kayit_eden As String
If mysql_connection.State = ConnectionState.Closed Then mysql_connection.Open()
For i = 6 To line - 1
line_isim = ds.Tables(0).Rows(i).Item(13).ToString
nereden = ds.Tables(0).Rows(i).Item(0).ToString
via = ds.Tables(0).Rows(i).Item(14).ToString
nereye = ds.Tables(0).Rows(i).Item(1).ToString
transit_sure = ds.Tables(0).Rows(i).Item(15).ToString
baslangic_tarihi = Convert.ToDateTime(ds.Tables(0).Rows(i).Item(2).ToString).ToString
e_kadar_gecerli = Convert.ToDateTime(ds.Tables(0).Rows(i).Item(3).ToString).ToString
kalem_kodu = ds.Tables(0).Rows(i).Item(7).ToString
fiyatlandirma = ds.Tables(0).Rows(i).Item(8).ToString
_20DRY = ds.Tables(0).Rows(i).Item(9).ToString
_40DRY = ds.Tables(0).Rows(i).Item(10).ToString
_40HDRY = ds.Tables(0).Rows(i).Item(11).ToString
_40HREF_NOR = ds.Tables(0).Rows(i).Item(12).ToString
kayit_eden = Environment.UserName.ToString
mysqlcommand.Parameters.AddWithValue("#line_isim", line_isim)
mysqlcommand.Parameters.AddWithValue("#nereden", nereden)
mysqlcommand.Parameters.AddWithValue("#via", via)
mysqlcommand.Parameters.AddWithValue("#nereye", nereye)
mysqlcommand.Parameters.AddWithValue("#transit_sure", transit_sure)
mysqlcommand.Parameters.AddWithValue("#baslangic_tarihi", baslangic_tarihi)
mysqlcommand.Parameters.AddWithValue("#e_kadar_gecerli", e_kadar_gecerli)
mysqlcommand.Parameters.AddWithValue("#kalem_kodu", kalem_kodu)
mysqlcommand.Parameters.AddWithValue("#fiyatlandirma", fiyatlandirma)
mysqlcommand.Parameters.AddWithValue("#20DRY", _20DRY)
mysqlcommand.Parameters.AddWithValue("#40DRY", _40DRY)
mysqlcommand.Parameters.AddWithValue("#40HDRY", _40HDRY)
mysqlcommand.Parameters.AddWithValue("#40HREF_NOR", _40HREF_NOR)
mysqlcommand.Parameters.AddWithValue("#kayit_eden", kayit_eden)
mysqlcommand.ExecuteNonQuery()
mysqlcommand.Parameters.Clear()
Next
If mysql_connection.State = ConnectionState.Open Then mysql_connection.Close()
End If
End If
ASPxGridView1.DataBind()

When combo box data selected, fill out textbox with data from Database

I am working on an application and I have a question, I have a Combo box that is bound to a table in my databse, when data is selected in the combo box I would like 'textbox 1' and 'textbox2' to be automatically filled out with data from the table, is this possible? so say for instance when I select 'Richard' on the combo box, 'Richards' 'Address1' and 'Postcode' are filled out in text boxes. I have a sample code that does this but it only seems to work with Int32, see insterted below.
Public Class Form1
Private Sub cmdGetByIdentifier_Click(sender As Object, e As EventArgs) Handles cmdGetByIdentifier.Click
If Not String.IsNullOrWhiteSpace(txtIdentifier1.Text) Then
Dim Identifier As Int32 = 0
If Int32.TryParse(txtIdentifier1.Text, Identifier) Then
txtCompanyName1.Text = GetCustomerNameByIdentifier(Identifier)
Else
MessageBox.Show("'" & txtIdentifier1.Text & "' is not a valid integer.")
End If
Else
MessageBox.Show("Must enter an identifier to get a company name.")
End If
End Sub
Private Sub cmdGetCustomer_Click(sender As Object, e As EventArgs) Handles cmdGetCustomer.Click
If Not String.IsNullOrWhiteSpace(txtIdentifier2.Text) Then
Dim Identifier As Int32 = 0
If Int32.TryParse(txtIdentifier2.Text, Identifier) Then
Dim Cust As Customer = GetCustomer(Identifier)
txtCompanyName2.Text = Cust.Name
txtContactName2.Text = Cust.ContactName
Else
MessageBox.Show("'" & txtIdentifier1.Text & "' is not a valid integer.")
End If
Else
MessageBox.Show("Must enter an identifier to get a company name.")
End If
End Sub
End Class
Module DatabaseOperations
Public Function GetCustomerNameByIdentifier(ByVal Identifier As Int32) As String
Dim CompanyName As String = ""
Dim Builder As New OleDb.OleDbConnectionStringBuilder With {.Provider = "Microsoft.ACE.OLEDB.12.0", .DataSource = IO.Path.Combine(Application.StartupPath, "Database1.accdb")}
Using cn As New OleDb.OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
cmd.CommandText = "SELECT CompanyName FROM Customer WHERE Identifier =#P1"
Dim NameParameter As New OleDb.OleDbParameter With {.DbType = DbType.Int32, .ParameterName = "P1", .Value = Identifier}
cmd.Parameters.Add(NameParameter)
cn.Open()
CompanyName = CStr(cmd.ExecuteScalar)
End Using
End Using
Return CompanyName
End Function
Public Function GetCustomer(ByVal Identifier As Int32) As Customer
Dim Customer As New Customer
Dim CompanyName As String = ""
Dim Builder As New OleDb.OleDbConnectionStringBuilder With {.Provider = "Microsoft.ACE.OLEDB.12.0", .DataSource = IO.Path.Combine(Application.StartupPath, "Database1.accdb")}
Using cn As New OleDb.OleDbConnection With {.ConnectionString = Builder.ConnectionString}
Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
cmd.CommandText = "SELECT Identifier, CompanyName,ContactName FROM Customer WHERE Identifier =#P1"
Dim NameParameter As New OleDb.OleDbParameter With {.DbType = DbType.Int32, .ParameterName = "P1", .Value = Identifier}
cmd.Parameters.Add(NameParameter)
cn.Open()
Dim Reader As OleDb.OleDbDataReader = cmd.ExecuteReader
If Reader.HasRows Then
Reader.Read()
Customer.Identifier = Identifier
Customer.Name = Reader.GetString(1)
Customer.ContactName = Reader.GetString(2)
End If
End Using
End Using
Return Customer
End Function
End Module
Public Class Customer
Public Property Identifier As Int32
Public Property Name As String
Public Property ContactName As String
Public Sub New()
End Sub
End Class
1.Refer Below Link To Fetch Data from Sql server
2.Create a Function Which Will Return your Data with ID as parameter
Dataadapter with dataset - sql sever
Not 100% sure about using Access but in theory what you would do is have a customer object
You would have a SQL Stored Procedure
Select * from Customers where id=#ID
...
Then a class
Public Class Customer
public property ID as Integer
Public property Name as string
public Property Surname as string
....
End Class
In your code where you access the data you would have something like
Public Function GetCustomerDetailsByID (byval CustomerID as Integer) As Customer ' Or whatever you want to return it as
Dim myCust as New Customer
' Code to access SQL
' Call your SQL procedure called GetCustByID(CustID)
With myCust
.Name = valueFromYourProcedure
End With
End Function
In your client app, you would then call the above, then assign the values to your controls i.e.
Dim SingleCustomer as Customer = GetCustomerDetailsByID(1) ' i.e. value form your dropdown
txtBoxName.Text = SingleCustomer.Name
Thats a very rough example and isnt fully complete but should give you some idea of how to go about this. Theres a lot of ways to do the above and everyone has their own way so you may need to do some extra research to be comfortable with it.
Hope this helps

How to Combine Multiple VB Functions / SQL Lookups into one vb.net function

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