How to split a joined column into its seperate columns and use the data? (VB.Net + SQL Management Studio) - sql

This is gonna be somewhat tricky to explain but I'll try to break it down. Note that this is created using VB.Net 2003.
I have a Web page which requires user to input data to save into SQL. They are required to fill in:
Course: {Select via drop-down table} \\ Variable name = Crse
Emp No: {Manually type the number} \\ Variable name = Emp
For the drop down list for Course, the data is obtained from an SQL table 'Course', with the columns:
| Course Code | Course Title |
Once input complete, I can then save the entry into my Emp_Course table in SQL using the query:
Dim updateState As String = "insert into EMP_COURSE" _
& "(Employee_No, CourseCode)" _
& "values('" & Emp.Text & "', " _
& "'"Crse.SelectedItem.ToString & "')"
Previously the drop-down list only needed the show Course Code, but now I'm required to add in the Course Title as well. Another thing to point out is that the Course Code has no fixed length.
Drop-down list sample:
Before:
A001
BX003
After:
A001 - Course A
BX003 - Course BX
Meaning I have to change the logic in populating the drop-down list:
Dim list As New SqlCommand("select CourseCode + ' - ' " _
& "+ CourseTitle as Course from [SQL].[dbo].[Course] " _
& "order by CourseCode", SQLDB)
Now comes my main issue, when I want to save my entry, the program obviously gives an error because the SQL still refers to the Course Code only, while my drop-down list is a Code + Description hybrid.
So since now I've made my course selection, how am I supposed to add to my SQL to update Emp_Course table to tell it to select the Course Code part of my hybrid selection?
I would just go to the Course table and just add a new Code + Title column and refer to that, but I have no authority to modify it and need to work around it.
Any other alternatives I can use?

Dim arr As String() = Crse.SelectedItem.ToString().Split(New Char() {"-"c})
Dim courseCode AS String = Trim(arr(0))
Dim updateState As String = "insert into EMP_COURSE" _
& "(Employee_No, CourseCode)" _
& "values('" & Emp.Text & "', " _
& "'"courseCode & "')"

Comments and explanations in line.
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Crse.DataSource = CreateDataSource()
'Course is the concatenated string returned from
'the database containing the CourseCode and the CourseTitle
Crse.DataTextField = "Course"
Crse.DataValueField = "CourseCode"
Crse.DataBind()
Crse.SelectedIndex = 0
End If
End Sub
Protected Function CreateDataSource() As DataTable
Dim dt As New DataTable
Using SQLDB As New SqlConnection("Your connection string")
'This selects the CourseCode as a separate column and the string called Course
'containing the CourseCode and the CourseTitle
Using cmd As New SqlCommand("select CourseCode, CourseCode + ' - ' + CourseTitle as Course from [SQL].[dbo].[Course] order by CourseCode", SQLDB)
SQLDB.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Return dt
End Function
Protected Sub UpdateDatabase()
Using SQLDB As New SqlConnection("Your connection string")
Using cmd As New SqlCommand("insert into EMP_COURSE (Employee_No, CourseCode) values(#EmpNo, #CourseCode);", SQLDB)
'I guessed at the SqlDbType. Check the database for the real data types.
cmd.Parameters.Add("EmpNo", SqlDbType.Int).Value = CInt(Emp.Text)
'Always use parameters to prevent SQL injection
'The SelectedValue will return the CourseCode
cmd.Parameters.Add("#CourseCode", SqlDbType.VarChar).Value = Crse.SelectedValue
SQLDB.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
UpdateDatabase()
End Sub
End Class

Split the value and get the course code as in the following code. Hope it helps.
Dim Str = Crse.SelectedItem.ToString
Dim strArr() As String
strArr = Str.Split(CType("-", Char()))
Dim CourseCode As String = strArr(0).Trim

Related

How can I get my information to pass from my VB application to my Access Database table?

So this is the code that I am using:
Public Class Form1
Dim dtmSystemDate As Date
Dim strResult As String
Dim Student As Double = Nothing
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBeginWorkout.Click
Dim cnn As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
Dim Start As String = "Start"
' Set date/time to today's date/time.
dtmSystemDate = Now()
' Convert txtIDNumber to a Double.
Try
Student = CDbl(txtIDNumber.Text)
Catch ex As Exception
End Try
' Determine if input is a valid ID number.
If Student >= 10000 And Student <= 99999 Then
MessageBox.Show("Your start time is " & dtmSystemDate.ToString("F"), "Welcome, Student # " & Student.ToString())
Else
MessageBox.Show("Please enter a valid College ID number", "Invalid Entry", MessageBoxButtons.OK, MessageBoxIcon.Exclamation
)
End If
cnn.ConnectionString = "provider = microsoft.jet.oledb.4.0; data source = C:\users\econnelly\My Documents\Access Databases\Fit Track.mdb"
cnn.Open()
cmd.Connection = cnn
cmd.CommandText = "insert into Fit Track (Student_ID,Start/Stop,Date/Time) values ('" & Student & "','" & Start & "', '" & dtmSystemDate & "')"
cmd.ExecuteNonQuery()
cnn.Close()
I am attempting to pass these defined variables to an Access Database and so far have been unsuccessful.
Whenever I try to run my program, I get the following error:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
This error is triggering from the cmd.ExecuteNonQuery() function though I am not sure why.
As of yet, I have been unable to get the information to populate into the database at all. Can anyone point me in the right direction as to how to address this issue?
I believe the problem is with the table name "Fit Track" that has a space in it.
You could use square brackets like [Fit Track]
or you could use single quotes like 'Fit Track'
I don't know the answer, but I've ran into trouble when using spaces or special characters, like slashes, in database Table or Column names. Also, I think your connection string is incorrect. You might also want to read a little bit about SQL injection, it can be dangerous.
EDIT: You might also need to import System.Data.Oledb

Take combobox SelectedIndex data and use in SELECT Query - VB.net

I'm a little desperate, hence why I'm here! I'm quite new to programming and have been given an assignment where I need to use a range of SQL queries to generate a simple HTML report table. There is also a user input, with them selecting the ClinicID from the comboBox and clicking a button to generate the report.
Basically, I have a comboBox that I have populated with 'ClinicID', as below. I have also made sure that SelectedIndex is working. I need to somehow use this in the SQL query method which I have also provided below.
Public Class frmReport1
'Set lsData for Clinics table
Dim lsData As List(Of Hashtable)
'On form load
Private Sub frmReport1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cboClinicID.DropDownStyle = ComboBoxStyle.DropDownList
'Instantiate new ClinicController object
Dim cController As ClinicController = New ClinicController
'Load ClinicID
lsData = cController.findId()
For Each clinic In lsData
cboClinicID.Items.Add(CStr(clinic("ClinicID")))
Next
End Sub
'Selected Index
Private Sub cboClinicID_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboClinicID.SelectedIndexChanged
Dim selectedIndex As Integer = cboClinicID.SelectedIndex
Dim selectedItem As Object = cboClinicID.SelectedItem
'Print in debug window
Debug.Print("Selected clinicID: " & selectedItem.ToString())
Debug.Print("Selected clinicID index: " & selectedIndex.ToString())
Dim htData = lsData.Item(selectedIndex)
End Sub
SQL query method - **note, I'm pulling from two different tables:
Where the '?' is, is where I assume I have to work in the 'SelectedItem' but I have no idea how!
Desired result: an html table outputted with these three selected fields.
Public Class ClinicOrderController
Public Const CONNECTION_STRING As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=PharmDB.accdb"
'Dim cController As ClinicController = New ClinicController
'Dim oController As OrderController = New OrderController
Public Function findClinicOrder() As List(Of Hashtable)
'Instantiates a connection object
Dim oConnection As OleDbConnection = New OleDbConnection(CONNECTION_STRING)
'Instantiates a list of hashtables
Dim lsData As New List(Of Hashtable)
Try
Debug.Print("Connection string: " & oConnection.ConnectionString)
oConnection.Open()
Dim oCommand As OleDbCommand = New OleDbCommand
oCommand.Connection = oConnection
'Stored in the CommandText property of the command object
'SELECT SQL statement
oCommand.CommandText = "SELECT clinics.clinic_id, orders.date_ordered, orders.total_price FROM clinics, orders WHERE clinics.clinic_id = orders.clinic_id AND clinics.clinic_id = ? ORDER BY clinics.clinic_id"
'Compiles the prepared statement
'oCommand.Prepare()
'Executes the SQL statement and stores the results in data reader object
Dim oDataReader = oCommand.ExecuteReader()
'Process data set in Hashtable
Dim htTempData As Hashtable
Do While oDataReader.Read() = True
htTempData = New Hashtable
htTempData("ClinicID") = CStr(oDataReader("clinic_id"))
htTempData("DateOrdered") = CStr(oDataReader("date_ordered"))
htTempData("OrderTotalPrice") = CStr(oDataReader("total_price"))
lsData.Add(htTempData)
Loop
Debug.Print("The record was found.")
Catch ex As Exception
Debug.Print("ERROR:" & ex.Message)
MsgBox("An error occured!")
Finally
oConnection.Close()
End Try
'Return list of hashtables to the calling function
Return lsData
End Function
Really, really appreciate any help here. Ive been struggling with this for more than 8 hours (not joking - I give you permission to laugh)
If i understand you correctly, you want to use your dropdown selected item in your WHERE clause. To achieve that , revise your joining using INNER JOIN with ON then place your filtering in WHERE condition. Hope code below will help.
SELECT clinics.clinic_id,
, orders.date_ordered
, orders.total_price
FROM clinics INNER JOIN orders ON clinics.clinic_id = orders.clinic_id
WHERE clinics.clinic_id = selectedItem.ToString()
ORDER BY clinics.clinic_id
if the selectedItem.ToString() did not work, you can try SelectedValue
Assuming that clinic_id is a numeric field in the database: (otherwise just surround it with single quotes (''))
string clinicID = cboClinicID.SelectedItem.ToString();
string sql = string.Format(#"SELECT clinics.clinic_id, orders.date_ordered, orders.total_price
FROM clinics, orders
WHERE clinics.clinic_id = orders.clinic_id
AND clinics.clinic_id = {0}
ORDER BY clinics.clinic_id", clinicID);
oCommand.CommandText = sql;
You can also do it like this:
string sql = "SELECT clinics.clinic_id, orders.date_ordered, orders.total_price " +
"FROM clinics, orders " +
"WHERE clinics.clinic_id = orders.clinic_id " +
"AND clinics.clinic_id = " + clinicID + " " +
"ORDER BY clinics.clinic_id";
Please provide code in vb.net
Here is my code, I want to display prize amount from table where class id is condition :
If class id is 3 then prize for that is display in my textbox named txtprize.text and class Id is displayed in list box.
Private Sub listClassID_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listClassID.SelectedIndexChanged
Dim classIdlist As String
classIdlist = New String(listClassID.SelectedItem.ToString)
Dim strSQL As String = "select [Prize Amount] from Master_Class WHERE [Class ID] =" & classIdlist
Dim dr As SqlDataReader
Try
con.Open()
cmd = New SqlCommand(strSQL, con)
dr = cmd.ExecuteReader()
If dr.Item(0) Then
txtPrize.Text = dr("[Prize Amount]").ToString
End If
dr.Close()
cmd.Dispose()
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub

Need help extracting variables from a While Loop in VB.Net

I'm a novice with my coding so forgive me if my question seems basic but I'm having some trouble extracting my variables from this While Loop in order to then use the results of my SQL query for validation.
This script below is the event handling for a login button on an .aspx form processing an email and login field that will be listed in a correlating MSSQL database:
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub submit_Click(sender As Object, e As EventArgs) Handles submit.Click
Dim Column1 As String
Dim Column2 As String
Dim SQL = "SELECT * FROM Logins WHERE Email='" & email.Text & "' AND Password='" & password.Text & "'"
Dim oSqlDataReader As System.Data.SqlClient.SqlDataReader = Nothing
Using oSqlConnection As New System.Data.SqlClient.SqlConnection("SERVER=[Server Name];UID=[User];PWD=[Pass];DATABASE=[Database Name]")
oSqlConnection.Open()
Using oSqlCommand As New System.Data.SqlClient.SqlCommand(SQL, oSqlConnection)
oSqlDataReader = oSqlCommand.ExecuteReader
While oSqlDataReader.Read
Column1 = oSqlDataReader(name:="Email")
Column2 = oSqlDataReader(name:="Password")
End While
End Using
oSqlConnection.Close()
End Using
If "Column 1 etc."
End if
End Sub
End Class
As far as I can tell my code is working with no errors but every time I try and create an If statement my Variable Column 1 and Column 2 are undeclared making them useless.
If anyone could help with the correct layout for my code or missing areas and an explanation as to where I've gone wrong that'd be great.
If you move the If block inside the loop, do you get closer to the behaviour that you're expecting?
Protected Sub submit_Click(sender As Object, e As EventArgs) Handles submit.Click
Dim Column1 As String
Dim Column2 As String
Dim SQL = "SELECT * FROM Logins WHERE Email='" & email.Text & "' AND Password='" & password.Text & "'"
Dim oSqlDataReader As System.Data.SqlClient.SqlDataReader = Nothing
Using oSqlConnection As New System.Data.SqlClient.SqlConnection("SERVER=[Server Name];UID=[User];PWD=[Pass];DATABASE=[Database Name]")
oSqlConnection.Open()
Using oSqlCommand As New System.Data.SqlClient.SqlCommand(SQL, oSqlConnection)
oSqlDataReader = oSqlCommand.ExecuteReader
While oSqlDataReader.Read
Column1 = oSqlDataReader(name:="Email")
Column2 = oSqlDataReader(name:="Password")
If "Column 1 etc....."
End if
End While
End Using
oSqlConnection.Close()
End Using
End Sub
It could be that your query is returning no rows or that the values returned are dbNull or nothing. I would check the data getting returned and error if appropriate.
Try running the query against the database directly. Are you getting a row back?
To avoid the error, you can declare the string as String.empty
Dim Column1 As String = String.empty
Or, when using it in the if statement check for nothing:
If Column1 Is Not Nothing AndAlso ...
Do not use string concatenation to build your sql query. Instead use sql-parameters to prevent sql injection and other issues.
I must admit that i don't know this syntax: oSqlDataReader(name:="Email"). Use following:
Dim email As String
Dim password As String
Dim sql = "SELECT * FROM Logins WHERE Email=#Email AND Password=#Password"
Using oSqlConnection As New System.Data.SqlClient.SqlConnection("SERVER=[Server Name];UID=[User];PWD=[Pass];DATABASE=[Database Name]")
Using oSqlCommand As New System.Data.SqlClient.SqlCommand(sql, oSqlConnection)
oSqlCommand.Parameters.Add("#Email", SqlDbType.VarChar).Value = email.Text
oSqlCommand.Parameters.Add("#Password", SqlDbType.VarChar).Value = password.Text
oSqlConnection.Open()
Using oSqlDataReader = oSqlCommand.ExecuteReader()
If oSqlDataReader.Read() Then
Dim emailColIndex = oSqlDataReader.GetOrdinal("Email")
Dim pwdColIndex = oSqlDataReader.GetOrdinal("Password")
email = oSqlDataReader.GetString(emailColIndex)
password = oSqlDataReader.GetString(pwdColIndex)
End If
End Using
End Using
End Using ' oSqlConnection.Close() not needed with using '
If email IsNot Nothing AndAlso password IsNot Nothing Then
End If
But instead of initializing two string variables you should implement a Login class that you can initialize and return from the method. You don't want to know the email and the password since you already have them.
Since this is ASP.NET i suggest to look at the available membership provider which are powerful and have a learning curve, but it's definitely worth the time.

How to Trigger Code with ComboBox Change Event

I have a created a database containing historical stock prices. On my form I have two comboboxes, ComboBox_Ticker and ComboBox_Date. When these comboboxes are filled I want to check the database and see if the respective data exists in the database. If it does I want to change the text of a label called Label_If_Present to "In Database".
My problem occurs with the change event. I want all of this to happen once I change the data in the textboxes. I have tried both the .TextChanged and .LostFocus events. The '.TextChanged' triggers the code to early and throws and error in my SQL command statement. The `.LostFocus' event doesn't do trigger my code at all.
Here is my current code:
Public databaseName As String = "G:\Programming\Nordeen Investing 3\NI3 Database.mdb"
Public con As New OleDb.OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source =" & databaseName)
Public tblName As String = "Historical_Stock_Prices"
Private Sub Change_Labels(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox_Ticker.TextChanged, ComboBox_Date.TextChanged
con.Close()
Dim dr As OleDbDataReader
con.Open()
If (File.Exists(databaseName)) Then
Dim restrictions(3) As String
restrictions(2) = tblName
Dim dbTbl As DataTable = con.GetSchema("Tables", restrictions)
If dbTbl.Rows.Count = 0 Then
Else
Dim cmd2 As New OleDb.OleDbCommand("SELECT * FROM " & tblName & " WHERE Ticker = '" & ComboBox_Ticker.Text & "' " & " AND Date1 = '" & ComboBox_Date.Text & "'", con)
dr = cmd2.ExecuteReader
If dr.Read() = 0 Then
'If record does not exist
Label_If_Present.Text = ""
Else
Label_If_Present.Text = "In Database"
End If
con.Close()
End If
Else
End If
End Sub
I have successfully implemented this concept on other forms within my project. This one is slightly different and I can't figure out why I can't get this one to work.
Handling the TextChanged event should work, however you need to set the DropDownStyle to DropDownList so that the Text property can only be a given value.
Then check to see that both comboboxes have values selected. Something like this should work:
If ComboBox_Ticker.Text <> "" AndAlso DateTime.TryParse(ComboBox_Date.Text, Nothing) Then

SQL like with multiple textboxes

For my company I have to create a customer database, which I manage over a VB.NET application.
The application has a few textboxes and a button to "Search" for a customer. If I type in the name of a customer the SQL Select statement is working and populating my datagrid.
But I want to be able to type in the name of the customer AND the street where he lives in. What is the best solution for this? using cases? using a lot of If statements?
Here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If True Then
Dim Conn As New MySqlConnection
Dim da As MySqlDataAdapter
Dim ds As New DataSet
Dim dt As New DataTable
Dim plz As String = plzTextBox.Text
Conn.ConnectionString = "server=localhost;uid=root;pwd=;database=wws; "
Dim sql As String = String.Empty
If vornameTextBox.Text <> String.Empty Then
sql = "vorname = " & vornameTextBox.Text.Trim
End If
If nachnameTextBox.Text <> String.Empty Then
AddCondition(sql, "nachname LIKE '%" & nachnameTextBox.Text.Trim & "%'")
End If
If emailTextBox.Text <> String.Empty Then
AddCondition(sql, "email LIKE '%" & emailTextBox.Text.Trim & "%'")
End If
If plzTextBox.Text <> String.Empty Then
AddCondition(sql, "plz LIKE '%" & plzTextBox.Text.Trim & "%'")
End If
If sql <> String.Empty Then
da = New MySqlDataAdapter("SELECT id,vorname,nachname,email,plz,strasse,nummer,stiege,stock,tuer FROM kunden WHERE " + sql, Conn)
da.Fill(dt)
DataGridView1.DataSource = dt
End If
Else
DataGridView1.ColumnCount = 1
DataGridView1.Rows.Add("1")
End If
End Sub
Thanks in advance!
You can avoid using lots of if statements if you really want, but all you're doing is shunting a load onto your SQL server instead of having it on the client.
The example here is one where you can use lots of if statements or ternary operators to determine how you build your SQL statement, putting a very light processing load on the client, or you can just insert the text value of each of your fields, followed by a percentage sign and surrounded by single quotes, thus making your SQL server evaluate the contents of those fields when it otherwise wouldn't if the field is blank.
It's possible query plan optimization would remove those superfluous field searches, and maybe it wouldn't. I'm typing this on my phone and so don't have anything available to test with.