I'm building a client database system for a travel company.
They want to be able to retrieve all of their customer emails with one click, and have it appear on a textbox on the page, where they can copy it off and paste it into Outlook.
Currently, the textbox is called emailList, and is invisible until the button called emailGet is clicked.
However, I have no idea how to make the text appear into the textbox from an SQL query.
My SQL query is: SELECT CEmail FROM Clients. That's pretty much it.
In pseudocode, what I'm trying to do is:
sqlQuery = "SELECT CEmail FROM Clients"
Execute select query and store results (in a variable? or maybe directly to the textbox?)
emailList.Text = Result of sqlQuery
Thank you! :)
Private Sub GetEmailAddresses()
Dim sText As String = String.Empty
Dim sConnString As String = String.Empty 'Put your connection string in here
Using cn As New OleDb.OleDbConnection(sConnString)
cn.Open()
Dim cmd As New OleDb.OleDbCommand("SELECT CEmail FROM Clients", cn)
Dim r As OleDb.OleDbDataReader = cmd.ExecuteReader()
If Not r.HasRows Then Exit Sub
Do While r.Read()
sText = sText & ";" & r.GetString(0)
Loop
cn.Close()
End Using
txtboxList.Text = sText
End Sub
Related
I am trying to convert VBA code into VB.net and I have made it to a point but I can't convert resultset into vb.net. RS was 'dim as resultset' in VBA, thought i could just change it to dataset but am getting errors with the '.fields' and other options?
Function GetG(sDB As String, sServ As String, sJob As String) As String
'sDB = Database name, sServ = Server\Instance, path = job.path
Dim conString As String = ("driver={SQL Server};server = " &
TextBox1.Text & " ; uid = username;pwd=password:database = " &
TextBox2.Text)
Dim RS As DataSet
Dim conn As SqlConnection = New SqlConnection(conString)
Dim cmd As SqlCommand
conn.Open()
'This is where my problems are occuring
cmd = New SqlCommand("SELECT [ID],[Name] FROM dbo.PropertyTypes")
Do While Not RS.Tables(0).Rows.Count = 0
If RS.Fields(1).Value = sJob Then
GetG = RS.Fields(0).Value
GetG = Mid(GetG, 2, 36)
Exit Do
End If
DataSet.MoveNext
Loop
conn.Close
End Function
Based on my understanding and some guesswork, here is what I came up with for what I think you're wanting.
As I stated in my comment above, it appears you can just use a WHERE clause to get the exact record you want (assuming a single instance of sJob appears in the name column).
Build the connectionstring off the input arguments, not controls on your form. That is after all why you allow for arguments to be passed along. Also note that there is a SqlCommandBuilder object that may be of interest. But for now
Function GetG(sDB As String, sServ As String, sJob As String) As String
'we'll pretend your connectionstring is correct based off of the sDB and sServ arguments
Dim conStr As String = ("driver={SQL Server};server = " & sServ & " ; uid = username;pwd=password:database = " & sDB)
'Create a connection and pass it your conStr
Using con As New SqlConnection(conStr)
con.Open() 'open the connection
'create your sql statement and add the WHERE clause with a parameter for the input argument 'sJob'
Dim sql As String = "SELECT [ID], [Name] FROM dbo.PropertyTypes WHERE [Name] = #job"
'create the sqlCommand (cmd) and pass it your sql statement and connection
Using cmd As New SqlCommand(sql, con)
'add a parameter so the command knows what #job holds
cmd.Parameters.Add(New SqlParameter("#job", SqlDbType.VarChar)).Value = sJob
'Now that have the command built, we can pass it to a reader object
Using rdr As SqlDataReader = cmd.ExecuteReader
rdr.Read()
'i admin i'm a little confused here on what you are
'trying to achieve so ID may not be what you are
'really wanting to get a substring of.
Return rdr("ID").ToString.Substring(2, 36)
End Using
End Using
End Using
End Function
An example to see if this is working could be to call a messagebox do display the result. For this example, I'm going to pretend that TextBox3 holds the sJob you're wanting. With that knowledge, you could simply do:
MessageBox.Show(GetG(TextBox2.Text, TextBox1.Text, TextBox3.Text))
This should then produce the result in a messagebox.
It seems that you're not filling your DataSet. So, when you try to loop through it, it's uninitialized or empty.
Check this answer to see an example: Get Dataset from DataBase
I need to use a combobox Id to make a sql insert and my combo only display the field "Name" of the table, and I kinda needed the field "Id" to make the insert, just like selectedValue on VB.NET
btw here's my code (VB6) to the call of the combobox select
Public Sub chamaCombo()
Dim con As New ADODB.Connection
Dim rsCombo As New ADODB.recordset
Dim conString As String
constring="Provider=SQLNCLI10;Server=MySv;Database=MyDb;Trusted_Connection=yes"
con.Open conString
rsCombo.Open "Select * from tbdClient", con, adOpenDynamic
Do While rsCombo.EOF <> True
cmb_client.AddItem rsCombo("Name").Value
cmb_client.ItemData(cmb_client.NewIndex) = rsCombo("IdClient").Value
txt_idclient.Text = rsCombo("IdClient").Value 'trying to pass to a txt but its no use
rsCombo.MoveNext
Loop
End Sub
I would declare a parallel collection that holds the value of the index and keyed by the SQL ID. Your code could look like this:
Private mCol As New Collection
Public Sub chamaCombo()
Dim con As New ADODB.Connection
Dim rsCombo As New ADODB.recordset
Dim conString As String
constring="Provider=SQLNCLI10;Server=MySv;Database=MyDb;Trusted_Connection=yes"
con.Open conString
rsCombo.Open "Select * from tbdClient", con, adOpenDynamic
Do While rsCombo.EOF <> True
cmb_client.AddItem rsCombo("Name").Value
mCol.Add("K_" & CStr(cmb_client.NewIndex), rsCombo("IdClient").Value)
rsCombo.MoveNext
Loop
End Sub
Private cmb_client_Click()
Dim ID As String
' Don't forget to test the ListIndex for a invalid value (ex: -1)
ID = mCol("K_" & CStr(cmb_client.ListIndex))
MsgBox ID
End Sub
Remember to clear the collection the same time where you are clearing the items on the combo box!
I am trying to convert VBA code to vb.net, im having trouble trying to search the database for a specific value around an if statement. any suggestions would be greatly appriciated.
thedatabase is called confirmation, type is the column and email is the value im looking for. could datasets work?
Function SendEmails() As Boolean
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
Dim intResponse As Integer
Dim confirmation As New ADODB.Recordset
Dim details As New ADODB.Recordset
On Error GoTo Err_Execute
Dim MyConnObj As New ADODB.Connection
Dim cn As New ADODB.Connection()
MyConnObj.Open( _
"Provider = sqloledb;" & _
"Server=myserver;" & _
"Database=Email_Text;" & _
"User Id=bla;" & _
"Password=bla;")
confirmation.Open("Confirmation_list", MyConnObj)
details.Open("MessagesToSend", MyConnObj)
If details.EOF = False Then
confirmation.MoveFirst()
Do While Not confirmation.EOF
If confirmation![Type] = "Email" Then
' Create the Outlook session.
objOutlook = CreateObject("Outlook.Application")
' Create the message.
End IF
If you want really convert your code to NET then I think you should remove the ADODB objects and use the System.Data.SqlClient classes. Of course some things are more difficult now because the ADO.NET really use a detached model to work with databases.
The semi-equivalent of your code using the ADO.NET classes
....
' Use Try/Catch not the On Error Goto....'
Try
Dim conStr = "Server=myserver;Database=Email_Text;User Id=XXXX;Password=XXXXX;"
Using MyConnObj = new SqlConnection(conStr)
' Getting all the details rows and columns, '
' but you should select only the columns needed here....'
Using cmdDetails = new SqlCommand("SELECT * FROM MessagesToSend", MyConnObj)
' You need only the rows with Type=Email, so no need to retrieve all the rows'
Using cmdConfirm = new SqlCommand("SELECT * FROM Confirmation_list " & _
"WHERE [Type] = 'EMail' ", MyConnObj)
MyConnObj.Open
Using da = new SqlDataAdapter(cmdConfirm)
Dim dt = new DataTable()
da.Fill(dt)
Using reader = cmdDetails.ExecuteReader()
While reader.Read()
For Each row in dt.Rows
... ' The Outlook app should be instanced outside the loop'
Next
Loop
End Using
End Using
End Using
End Using
End Using
Catch x As Exception
MessageBox.Show("Error:" & x.Message)
End Try
Possibly the usage of the Type column is causing an issue. You might be able to get this working by doing the following:
confirmation.Fields("Type").Value
instead of
confirmation![Type]
but I would recommend you look into ADO.NET isntead of using ADODB as this is quite old now.
guys i want to build an efficient searching tool in vb to search data from my database in mysql where i have stored paragraphs of some information. i want the search to return multiple results like google does but in a textbox in the form of 2-3 paragraphs of the same concept.Also to make the search more efficient i want to include the substring feature that is the % sign in the select query. can anyone tell me how to implement these two features ? here is my basic search code that returns just a single paragraph stored in the table into my result textbox that i hide first and then show when the results appear.
If TextBox1.Text = "" Then
MsgBox("Please Enter a Keyword")
Else
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = "Server=localhost;UserID=root;Password=admin674;Database=db1"
Dim myadapter As New MySqlDataAdapter
conn.Open()
Dim sqlquery = "select text from text where name like '" & TextBox1.Text & "'"
Dim mycommand As New MySqlCommand
mycommand.Connection = conn
mycommand.CommandText = sqlquery
myadapter.SelectCommand = mycommand
Dim mydata As MySqlDataReader
mydata = mycommand.ExecuteReader
If mydata.HasRows = 0 Then
MsgBox("Data Not Found")
TextBox1.Clear()
TextBox2.Clear()
Else
mydata.Read()
TextBox2.Text = mydata.Item("text")
TextBox2.Show()
End If
You already answered one question yourself - how to do a substring search, simple add % to your query:
Dim sqlquery = "select text from text where name like '%" & TextBox1.Text & "%'"
(ideally, instead of supplying search value in-line you would use parametrized query, which, among other things would help avoid SQL Injection.
As for the second part - you are already using DataReader, all you have to do is instead using a single mydata.Read() command - loop thru all its results. Replace
mydata.Read()
TextBox2.Text = mydata.Item("text")
TextBox2.Show()
with
Dim sb as New StringBuilder()
While mydata.Read()
sb.AppendLine(mydata("text"))
End While
TextBox2.Text = sb.ToString()
TextBox2.Show()
This approach uses StringBuilder class which is an efficient way to concatenate multiple strings.
P.S. Don't forget to close your DataReader and Connection after use.
I have a form where i want to enter Sr. Nos for machines.it have a combo box where i have to choose the invoice no saved in another table along with its corresponding qty of machines.
When i am entering machine details it should say me as "enter Sr no. for X'th/Y'th machine where y is the total qty saved in db and x is the no. of sr no. i have saved+1 "
It should also allow me to save the no. some where.. i mean in any variable so that if i pause my work in between and after word if continue it should say me "enter detail for X'th/Y'th" not "1'st/Y'th"
I am using this code:
Private Sub get_qty()
Dim qtySql As String = "SELECT * FROM invoice1 where chalan_no='" & cmbChal_no.Text & "'"
cnnOLEDB.Open()
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(qtySql, cnnOLEDB)
Dim dr As OleDb.OleDbDataReader = cmd.ExecuteReader
If dr.Read = True Then
qnty = dr("qty")
End If
cnnOLEDB.Close()
End Sub
Private Sub Srno_enter()
Dim noSql As String = "SELECT count(sr_no) FROM Vendor_machine GROUP BY(chalan_no) having chalan_no='" & cmbChal_no.Text & "'"
cnnOLEDB.Open()
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(noSql, cnnOLEDB)
' Suggest code retrieve count(sr_no) <--------------------------
cnnOLEDB.Close()
End Sub
private sub show()
lblMachine= 'Result of count(sr_no)' "/" qnty
end sub
Please suggest me the code for same.. thank you..
Just use an Identity column in your database and let the database engine do the work of creating the next free number.
If you wrote a stored procedure to do the insert, you could return the serial number as an output parameter