Populate listbox with alias values using SQL select statment - sql

I have two columns in MS SQL table (ID, and Name) that I want to use to populate a list box with. I would like to show the Name values (as alias?) in the list box, however when the user selects the item I want the ID value to be returned not the Name value. My code below just adds the values into the list box from the Name column.
Me.listName.Items.Clear()
Dim strName As String = "select SetName from " & tb
Dim con As String = sConnectionString
Dim com As New SqlCommand(strServiceType, New SqlConnection(con))
com.Connection.Open()
Dim dr As SqlDataReader
Dim ColumnValue As String = Nothing
dr = com.ExecuteReader
While dr.Read
ColumnValue = (dr.GetValue(0)).ToString
listName.Items.Add(ColumnValue)
listName.Sorted = True
End While
com.Connection.Close()
I'm not sure how to apply the logic above to get the associated ID value besides running another select statement on the list box SelectedIndexChanged event.
Thank you

If I'm not mistaken, you simply need to edit your sql to pull both ID and Name, then edit your addition of an item to your list box to add a new list item instead.
i.e.
listName.Items.Add(New ListItem("TEXT","VALUE"))

Related

Display Multiple Values in Text Boxes based on a Combo Box Value

I have one table - tblMAIN
I have 4 ID Fields - mainID, FatherID, MotherID and FullName
1 Form - frmMAIN
1 Combo Box - cboMAIN
2 Text Boxes - txtFATHER, txtMOTHER
I am trying to write a SQL statement in VBA that will select a record in the combo box cboMAIN and by doing that selection, two text boxes are populated.
Robert is selected in the cboMAIN, Robert has a MainID of 20
Robert mother is Ruth, she has a MainID of 30
Robert's father's MainID is 40
So in txtFather it will display record 40 / FullName and in txtMother it will display FullName for record MainID30.
I would like to add text fields and show Ruth's mother and Robert's father's father.
Here is an idea I have, but not sure what to do next.
Dim sqlME As String
Dim sqlFATHER As String
Dim db As Database
Dim rs As DAO.Recordset
sqlFATHER = "SELECT * FROM tblMAIN WHERE MainID = " & Forms![MAIN]![cboMAIN] & ";"
'AND NOT SURE WHAT I NEED TO DO HERE!
Set db = CurrentDb
Set rs = db.OpenRecordset(sqlFATHER)
Me.txtFather.Value = rs!FullName
Set rs = Nothing
Set db = Nothing
VBA setting value of UNBOUND textbox will show same value for every record.
This data is recursive in nature and Access SQL doesn't easily manipulate data of recursive nature. Other database platforms have utility to better deal with.
Build a self-join query object named qryAncestors:
SELECT tblMain.mainID, tblMain.FullName, tblMain_1.FullName AS Father,
tblMain_2.FullName AS Mother, tblMain_3.FullName AS PGFather,
tblMain_4.FullName AS PGMother, tblMain_5.FullName AS MGFather, tblMain_6.FullName AS MGMother
FROM tblMain AS tblMain_6
RIGHT JOIN (tblMain AS tblMain_5
RIGHT JOIN (tblMain AS tblMain_4
RIGHT JOIN (tblMain AS tblMain_3
RIGHT JOIN (tblMain AS tblMain_2
RIGHT JOIN (tblMain AS tblMain_1
RIGHT JOIN tblMain
ON tblMain_1.mainID = tblMain.FatherID)
ON tblMain_2.mainID = tblMain.MotherID)
ON tblMain_3.mainID = tblMain_1.FatherID)
ON tblMain_4.mainID = tblMain_1.MotherID)
ON tblMain_5.mainID = tblMain_2.FatherID)
ON tblMain_6.mainID = tblMain_2.MotherID;
Then options to use that query:
reference query as combobobox RowSource then textbox ControlSource references combobox columns by index
=[cboMain].Column(2)
textbox ControlSource uses DLookup() expression, such as:
=DLookUp("Father", "qryAncestors", "mainID=" & mainID)
textbox ControlSource calls VBA custom function to return a value, like:
=GetAncestor(mainID, "Father")
Function GetAncestor(intID As Integer, strAnc As String)
GetAncestor = DLookUp(strAnc, "qryAncestors", "mainID=" & intID)
End Function
If you want to go beyond grandparents to any level, approach would have to be quite different. Recursive procedure is tricky. A function to return FullName of ancestor could be like:
Function GetAncestor(intID As Integer, intGen As Integer, strParent As String)
Dim x As Integer
GetAncestor = intID
For x = 1 To intGen
GetAncestor = DLookup(strParent, "tblMain", "mainID=" & Nz(GetAncestor,0))
Next
GetAncestor = DLookup("FullName", "tblMain", "mainID=" & Nz(GetAncestor,0))
End Function
To get ancestor of specific generation, call function: GetAncestor(mainID, 1, "MotherID")

How to put a value from SQL number format column to a double in VB.net?

I have selected from SQL like this
SELECT MAX(receivecount) FROM config
which shows only one value of 20161.
so now I can't take that number and put it in a double or a int32. The column name is ReceiveCount
Current what I have is this
Dim ads2 As New DataTable
strrs2 = "SELECT MAX(recievecount) FROM tblcmconfig"
Using ads23 As OracleDataReader = GetDataReader(strrs2, CommandType.Text, ExecuteType.Execute)
ads2.Load(ads23)
End Using
Dim dugaar As Double '= Convert.ToDouble(ids)
dugaar = Double.Parse(ads2("recievecount").ToString)
After this I am trying to put that value in a textedit.editvalue as that textedit is numbers only enterable.
Assuming your datatable is populated correctly. You either need to give the MAX(recievecount) a name in the select statement like:
MAX(recievecount) as rc
Then
Double.Parse(ads2(0)("rc").ToString)
Or you can refer to the row and and column numers:
Double.Parse(ads2(0)(0).ToString)

How to use a query as a control source for a textbox on a form?

I have a form myForm that's binded to a table tbl in my database. (I don't know if binded is the correct term, but It shows records from tbl on by one.)
In the form:
contact: textbox, binded to tbl.contact.
dailyCount: textbox, should show the amount of contacts entered today.
In the table:
contact
dateEntry
The query I want to use is:
SELECT count(*)
FROM tbl
WHERE contact = currentContact
AND month(dateEntry) = month(now)
AND day(dateEntry) = day(now)
AND ear (dateEntry) = year(now)
Where currentContact is the contact that is showing on the form now.
I tried putting the query in the dailyCount dataSource, but It's not working. When I click on the three dots on datasource to access the wizard, I get a window to build functions and not queries.
How do I get the currentContact showing on the form into the query?
There are multiple ways to do this. For a couple of reasons, I don't like to hardcode queries in the datasource of a specific field, and I mostly build/assign all my queries in VBA. So here's how I would do it.
In the load event of you form :
Private Sub Form_Load()
Dim SQL As String
Dim RST As Recordset
dim theCOntact as string ' Change accordingly
theCOntact = Me.currentContact ' I don't know how your fields are named, so change accordingly
SQL = "SELECT count(*) AS cnt FROM tbl WHERE contact = " & theContact & "' AND month(dateEntry) = month(now) AND day(dateEntry) = day(now) AND Year(dateEntry) = year(now)"
Set RST = CurrentDb.OpenRecordset(RST)
If RST.BOF Then
dailyCount.Value = RST!cnt
Else
dailyCount.Value = 0
End If
End Sub
Assuming your contact field is string, if its a number remove the quotes in the SQL
Probably the simplest approach is to use the DLookup function with an associated query:
Create and save a named query with your SQL code or equivalent. Let's call it "qryDailyCount". Note that it should be modified to look something like this (in particular, name the column and change the record reference to a GROUP BY for now):
SELECT count(*) as DailyCount
FROM tbl
WHERE month(dateEntry) = month(now)
AND day(dateEntry) = day(now)
AND year (dateEntry) = year(now)
GROUP BY contact
In the dailyCount textbox, set the Control Source to something like this:
=DLookUp("Count";"qryDailyCount";"contact = [contact]")
(Note that if the contact field is a text field, you must enclose it with single quotes.)

Using textbox values in IN statement

I'm trying to get this to work? How can I set a textbox to be used in an IN() statement? I would like users to be able to list out countries they'd like to query on
SELECT *
FROM Table
WHERE CountryID IN (forms!frmImport!txtCountries)
You can't just put the name of the textbox directly into the SQL string.
Instead, you need to use the content of the textbox to build a SQL string like this:
SELECT * FROM Table WHERE CountryID IN (1,2,3)
If your users enter a comma-separated list of CountryIDs into the textbox, you can build the SQL like this:
Dim SQL As String
SQL = "SELECT * FROM Table WHERE CountryID IN (" & Forms!frmImport!txtCountries & ")"
But I wouldn't do it this way because it's simple, but prone to input errors and SQL injection.
A better way would be to use a list box, set the Multi Select property (so that multiple entries can be selected) and fill it with a list of all available countries.
Then, the user can select the ones that he wants, and you can build the SQL string using the selected items from the listbox:
Dim ListItem As Variant
Dim CountryList As String
Dim SQL As String
For Each ListItem In Forms!frmImport!lstCountries.ItemsSelected
If CountryList > "" Then
CountryList = CountryList & ","
End If
CountryList = CountryList & ListItem
Next
SQL = "SELECT * FROM Table WHERE CountryID IN (" & CountryList & ")"

how to get data to textbox from the database

I have a form with one combo box and text box, and an SQL database
named balance with two columns; one as customername and the other as obbalance.
I had bound all of the customer name to the combo box, now what I have to do is,
when a user selects a customer name from the combo box, the text box should show the obbalance of the selected customername; here, the customer name will not be repeated - only one name per customer.
What can I do? Please help me.
Dim conectionstring As String
conectionstring = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\SHOPPROJECT\SHOPPROJECT\shop.mdf;Integrated Security=True;User Instance=True"
Dim ST As String = ComboBox1.SelectedText
Dim sqlcon As New SqlConnection(conectionstring)
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = " & " '" & ST & "'" & "", sqlcon)
MessageBox.Show(TextBox1.Text)
Dim result As Object
Try
sqlcon.Open()
' Dim sdr As SqlDataReader = sqlcmd.ExecuteReader()
result = sqlcmd.ExecuteScalar()
If result IsNot Nothing Then
TextBox1.Text = result.ToString()
MessageBox.Show(TextBox1.Text)
End If
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
I've tried this, but I can't see the value in the text box, and obbalance is a floating-point value from the SQL database.
If you're updating a text box, is this a single result (scalar value)? If so, the first thing I'd do is use ExecuteScalar not ExecuteReader. Then, use debug mode with breakpoints to get a better idea of what is actually happening. It may simply be that you're not getting any results.
Note: I'm assuming the bad coding practice (in-line sql statement, hard-coded connection string, etc.) are for clarity. If they're not, fix them.
Make the follwing changes:
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = '" & ST & "'", sqlcon)
TextBox1.Text = sdr.GetString(yourColumnIndex)
ComboBox1.SelectedText returns the highlighted (selected) text on the ComboBoxControl. That will be empty if you haven't use your mouse to select a portion of its text or hold the shift while you are pressing the direction keys on your keyboard. And that's probably why your query returns ZERO RECORDS.
Use the following instead:
Dim ST As String = ComboBox1.SelectedItem.Text
Set a breakpoint and ensure you are getting the value for OBBALANCE (see if you are getting any rows period might be good). Also, make sure you can only get one row, as you are iterating forward, even when you only need one value.
Better yet, consider ExecuteScalar, which only returns a single value. While you are at it, parameterize the SQL query so you don't get SQL injected.
UPDATE: Just change it here:
sdr = sqlcmd.ExecuteReader()
to something like
Dim s as String = sqlcmd.ExecuteScalar()
Then use s as your textbox value. You may have to ToString() the value or otherwise cast as string, as I believe the ExecuteScalar() returns an object.