Retrieve data from a specific row entered by inputbox - sql

I have a button and once clicked you are required to enter the customersID and once entered the data from that whole row should then load into the text box's, checkbox etc but when i do it, it prompts me with my own error i created saying Customer not found because it cant locate the ID of some sort? Any help appreciated!
In my opinion - When it loads * (All) from where ID is i am thinking it is only loading in all that data from that specific row at that Customer ID (in which i want) so i could use rows.items etc to load in my required information? Is this correct or? In general i just need help retrieving the data and putting it into my text boxes and such.
Code:
Private Sub Client(ByVal ans As String)
If con.State = ConnectionState.Closed Then con.Open()
cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "Select * FROM tbl WHERE ID = ?"
cmd.Parameters.Add("?", OleDbType.VarChar).Value = ans
If cmd.ExecuteNonQuery() = 0 Then
MsgBox("Does not exist!", MsgBoxStyle.Critical, "Enter new ID!")
Else
MessageBox.Show("Now loaded.", "Search Complete!", MessageBoxButtons.OK, MessageBoxIcon.Information)
If con.State = ConnectionState.Closed Then con.Open()
'create data adapters
sql = "Select * from tbl"
da = New OleDbDataAdapter(sql, con)
da.Fill(ds, "tbl")
RecCnt = ds.Tables("tbl").Rows.Count 'how many records in ds
'assign data to lables
TxtCI.Text = ds.Tables("tbl").Rows(0).Item(0)
con.Close()
End If
cmd.ExecuteNonQuery()
con.Close()
End Sub
Caller (Search button):
Client(custid)

ExecuteNonQuery cannot work correctly with a SELECT statement. The returned value is the number of the rows affected but a SELECT statement doesn't change, insert or delete any row, so it is always zero.
You should use ExecuteReader (and this removes also the need to use an OleDbDataAdapter, a DataTable/Dataset and the long winded statement lines to retrieve values from the DataSet/Tables/Rows/Columns hierarchy
If con.State = ConnectionState.Closed Then con.Open()
cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "Select * FROM tblcustomer WHERE CustomerID = ?"
cmd.Parameters.Add("?", OleDbType.VarChar).Value = ans
Dim reader As OleDbDataReader = cmd.ExecuteReader()
if reader.Read() Then
TxtCI.Text = reader(0).ToString()
TxtName.Text = reader(1).ToString()
... and so on ...
Else
MsgBox("Customer Does not exist!", ....)
Notice that you could substitute the column index (0,1,2 etc...) with the column name ("CI", "Name" etc...). This is somewhat better because it doesn't depend on the order returned by the SELECT * query (Of course, if you change the columns names you have the same problem but, at least, you should know about the change)

Related

Insert text into MS access cells

i am begginer in visual basic and i want to insert text into cells in column in MS access but i doesn't find, how could i do that.
Here is code i tried:
Private Sub UpdateDataBase2()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
datafile = "F:\Test Database\Database.accdb"
conString = provider & datafile
myConnection.ConnectionString = conString
myConnection.Open()
Dim str As String
str = "Insert into TABLA([LABELS]) Values (?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("LABELS", CType(TextBox1.Text, String)))
Select Case panelCount
Case 1
' TextBox1.Text = cmd.Add("LABELS").Rows(0).Item(1).ToString()
Case 2
' str = "Insert into TABLA([LABELS]) Values (?)"
'cmd.Parameters.Add(New OleDbParameter("LABELS", CType(TextBox1.Text, String)))
End Select
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
myConnection.Close()
End Sub
In this application, i made a dynamics panels and labels.(dynamics is for me generated in code)
panelcount is variable which saves to another MS acces database count of dynamics panels. I want to save text from labels to database systematically(it means: text from label 1 insert to cell 1.), but every code i tried was not function for me.
I know i have to use loop, but first i want to try if code works.
Sorry for my english.
Any solution?
Database objects like Connection and Command should be declared in the method where they are used so they can be disposed.
Use Using...End Using blocks to ensure that your database objects are closed and disposed even if there is an error.
Insert creates a new record. If you want to Update an existing record you will need the primary key value for the record you want to update.
Dim Str = Update TABLA Set [LABELS] = ? Where ID = ?
Then you will need a second parameter.
cmd.Parameters.Add("ID", OleDbType.Integer).Value = intID
You will need to declare and provide a value for intID.
Don't show a message box while a connection is open.
Private Sub OPCode()
Try
Dim Str = "Insert into TABLA([LABELS]) Values (?)"
Dim ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Test Database\Database.accdb"
Using myConnection As New OleDbConnection(ConStr),
cmd As OleDbCommand = New OleDbCommand(Str, myConnection)
cmd.Parameters.Add("LABELS", OleDbType.VarChar).Value = TextBox1.Text
myConnection.Open()
cmd.ExecuteNonQuery()
End Using 'Closes and disposes the connection and disposes the command
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Updating Table from vb to Access using ConnectionString

Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Try
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\Comp-296\Project1\Project1\Game_time.mdb"
con.Open()
cmd.Connection = con
cmd.Connection = con
cmd.CommandText = ("UPDATE User_Name SET User_Name = #User_Name, Game_Name = #Game_Name, Score = #Score, Time/Date = #Time/Date")
cmd.Parameters.Add("#User_Name", SqlDbType.VarChar).Value = txtUser.Text
cmd.Parameters.Add("#Game_Name", SqlDbType.VarChar).Value = txtGame.Text
cmd.Parameters.Add("#Score", SqlDbType.VarChar).Value = txtScore.Text
cmd.Parameters.Add("#Time/Date", SqlDbType.DateTime).Value = txtDate.Text
cmd.ExecuteNonQuery()
MessageBox.Show("Data Update successfully")
con.Close()
Catch ex As System.Exception
MessageBox.Show("Data Update has failed")
End Try
End Sub
The code is giving an Exception is an ArgumentException and also :Keyword not supported: 'provider'.
You are using Access. This database cannot be opened using the classes in System.Data.SqlClient. These classes are used when you want to connect to Sql Server, Sql Server Express or LocalDB.
If you want to reach an MSAccess database you need the classes in System.Data.OleDb and these classes are OleDbConnection, OleDbCommand etc...
Said that, please note, that your field Date/Time will give you headaches. Change that name or put always square brackets around it because the / will be interpreted as the division operator
So your code could be:
Using con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\Comp-296\Project1\Project1\Game_time.mdb")
Using cmd = new OleDbCommand("UPDATE User_Name
SET User_Name = #User_Name,
Game_Name = #Game_Name,
Score = #Score, [Time/Date] = #dt", con)
con.Open()
cmd.Parameters.Add("#User_Name", OleDbType.VarWChar).Value = txtUser.Text
cmd.Parameters.Add("#Game_Name", OleDbType.VarWChar).Value = txtGame.Text
cmd.Parameters.Add("#Score", OleDbType.VarWChar).Value = txtScore.Text
cmd.Parameters.Add("#dt", OleDbType.Date).Value = Convert.ToDateTime(txtDate.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Data Update successfully")
End Using
End Using
Other notes:
Disposable objects like the connection and the command should be enclosed inside a Using Statement to be disposed and closed as soon as possible.
The time field requires a DateTime value not a string. If you pass a string you will face the automatic conversion made by the engine and sometime the engine is unable to produce a valid date from your input string. This will raise another exception (DataType mismatch). Better check and convert the value before passing it.
Also the type of the parameters should be from the OleDbType enum.

How to insert listview items into 3 different tables VB.net

I'm trying to make a library system. I have a listview and it contains items to be inserted into different tables, (b_borrow_tbl, for the books , d_borrow_tbl for the multimedia, and m_borrow_tbl for the module).
I'm using this code to insert items to b_borrow_tbl:
Dim myconnection As New SqlConnection("Data Source = .\SqlExpress;Initial Catalog = librarysystemdb; Integrated Security = True")
selecteduser = cmb_borrower.SelectedValue
myconnection.Open()
For xa = 0 To ListView1.Items.Count - 1
Dim mycommand As New SqlCommand("Insert into b_borrow_tbl (bid,user_id,dateborrowed,aid,status) values(#bid,#user,#dateborrowed,#admin ,'" & "Borrowed" & "')", myconnection)
mycommand.Parameters.AddWithValue("bid", ListView1.Items(xa).SubItems(5).Text)
mycommand.Parameters.AddWithValue("user", selecteduser)
mycommand.Parameters.AddWithValue("dateborrowed", datestring)
mycommand.Parameters.AddWithValue("admin", LoginPage.admin)
mycommand.ExecuteNonQuery()
myconnection.Close()
Next
MsgBox("Transaction Saved")
ListView1.Items.Clear()
myconnection.Close()
End Sub
Here's one possibility. Note that I can't give you exact code because I don't know the structure of your other tables...so, with that caveat...
Dim myconnection As New SqlConnection("Data Source = .\SqlExpress;Initial Catalog = librarysystemdb; Integrated Security = True")
selecteduser = cmb_borrower.SelectedValue
myconnection.Open()
For xa = 0 To ListView1.Items.Count - 1
Dim itemType as String
itemType = ListView1.Items(xa).Subitems(6).Text ' Not sure abt col #
if itemType="Books" Then
Dim mycommand As New SqlCommand("Insert into b_borrow_tbl (bid,user_id,dateborrowed,aid,status) values(#bid,#user,#dateborrowed,#admin ,'" & "Borrowed" & "')", myconnection)
mycommand.Parameters.AddWithValue("bid", ListView1.Items(xa).SubItems(5).Text)
mycommand.Parameters.AddWithValue("user", selecteduser)
mycommand.Parameters.AddWithValue("dateborrowed", datestring)
mycommand.Parameters.AddWithValue("admin", LoginPage.admin)
mycommand.ExecuteNonQuery()
End If
If itemType="Multimedia" Then
mycommand.SqlCommand="Insert into d_borrow_table( field1,field2,etc) values (#parm1,#parm2,...)
mycommand.Parameters.Clear()
mycommand.Parameters.AddWithValue("#param1",value)
' etc
mycommand.ExecuteNonQuery()
' Then repeat by changing command text for third table
' clearing/defining parameters, then executing the query
End If
myconnection.Close()
Next
MsgBox("Transaction Saved")
ListView1.Items.Clear()
myconnection.Close()
End Sub
All we're doing here is "resetting" the "mycommand" variable with a new INSERT statement, clearing the parameters, and redefining them for the second and third inserts. Note that the connection isn't closed until after all three inserts have fired. You'll obviously need to replace the "placeholders" of "field1,field2" and #param1,#param2 etc with the actual fields from your tables, but I think that should give you a push in the right direction.

Creating new records in MSACCESS Table

I am attempting to create a new record from vb.net to an msaccess table, which i am able to do, but i have to add in the next consecutive ID number for it to actually save. For instance, if the next ID in the Access DB is 4, i have to type in 4 in the id textfield on my form. Code below:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim sqlinsert As String
' We use the INSERT statement which tells our program to add the information
' from the Forms Text fields into the Databases columns.
sqlinsert = "INSERT INTO Table1(Title, YearofFilm, Description, Field1, ID)" & _
"VALUES(#Title, #YearofFilm, #Description, #Field1, #ID)"
Dim cmd As New OleDbCommand(sqlinsert, con1)
' This assigns the values for our columns in the DataBase.
' To ensure the correct values are written to the correct column
cmd.Parameters.Add(New OleDbParameter("#Title", TextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#YearofFilm", Convert.ToInt32(TextBox2.Text)))
cmd.Parameters.Add(New OleDbParameter("#Description", TextBox3.Text))
cmd.Parameters.Add(New OleDbParameter("#Field1", TextBox4.Text))
cmd.Parameters.Add(New OleDbParameter("#ID", Convert.ToInt32(TextBox5.Text)))
' This is what actually writes our changes to the DataBase.
' You have to open the connection, execute the commands and
' then close connection.
con1.Open()
cmd.ExecuteNonQuery()
con1.Close()
' This are subs in Module1, to clear all the TextBoxes on the form
' and refresh the DataGridView on the MainForm to show our new records.
ClearTextBox(Me)
RefreshDGV()
Me.Close()
End Sub
How can i tell textbox5 which is the ID field, to be the next number in the access db?
Open your Access database, show the structure of your table and change the ID field type from numeric to AutoNumber.
Now your code don't need to pass anything to Access because the number will be handled automatically from Access.
You could just add these lines to your code to get back the number assigned by Access to your field
Dim sqlinsert As String
sqlinsert = "INSERT INTO Table1(Title, YearofFilm, Description, Field1)" & _
"VALUES(#Title, #YearofFilm, #Description, #Field1)"
Dim cmd As New OleDbCommand(sqlinsert, con1)
cmd.Parameters.Add(New OleDbParameter("#Title", TextBox1.Text))
cmd.Parameters.Add(New OleDbParameter("#YearofFilm", Convert.ToInt32(TextBox2.Text)))
cmd.Parameters.Add(New OleDbParameter("#Description", TextBox3.Text))
cmd.Parameters.Add(New OleDbParameter("#Field1", TextBox4.Text))
con1.Open()
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
cmd.CommandText = "SELECT ##IDENTITY"
Dim assignedID = Convert.ToInt32(cmd.ExecuteScalar())
' Eventually
TextBox5.Text = assignedID.ToString
con1.Close()
......
See also
How to retrieve last autoincremented value in MS-Access like ##Identity in Sql Server
Create a SELECT statement to retrieve the Max number form the table and add one to it. I do not know VB.Net, so it should be something like.
maxQry = "SELECT Max(IDColumnName) As MaxID FROM theTableName;"
Dim cmd As New OleDbCommand(maxQry, con1)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read()
TextBox5.Text = dr("MaxID").ToString
End While
End If
Unless the field is an AutoNumber type you do not have to worry about it at all.

Insert selected records to another table in VB.Net and access

My name is Sarfaraz. I am developing a project in VB.Net and MSAccess 2007. I have a listbox control that is being populated from a table in Access called items. I am using a combination of two listbox's to select differnt values. I want to get the rate of the individual item when I hit the save button. The values are stored in a clients table. I am storing the data like Sugar=5 Biscuits=10 etc.
I am using a VB6 textbox and Recordset and need to know how I would implement the same thing in VB.Net
I have figured the answer but it is taking a very long time to perform the task and my system is going in a busy mode for almost 10 seconds. Is there anything wrong in this code Please have a look
Thank you.
Here is my code
Con.Open()
For l_index = 0 To ListBox2.Items.Count - 1
query = ("select Investigation.rate " & _
"from Investigation WHERE (((Investigation.Investigation) = '" & ListBox2.Items(l_index) & "'));")
Dim cmd2 As New OleDbCommand(query, Con)
'Con.Open()
Dim reader As OleDbDataReader = cmd2.ExecuteReader
reader.Read()
'Console.WriteLine(reader(0))
txtrate.Text = reader.GetString(0)
reader.Close()
'Con.Close()
' Con.Close()
'End If
Dim SqlString As String = "Insert Into patients (Receipt_No, OPD_MRD,Patientname,Investigation,Receipt_date,Receipt_time,rate) Values (?,?,?,?,?,?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, Con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("Receipt_No", txtreceiptno.Text.Trim())
cmd.Parameters.AddWithValue("OPD_MRD", txtopd.Text.Trim())
cmd.Parameters.AddWithValue("Patientname", txtname.Text.Trim())
cmd.Parameters.AddWithValue("Investigation", CStr(ListBox2.Items(l_index)).ToString())
cmd.Parameters.AddWithValue("Receipt_date", lbldate.Text)
cmd.Parameters.AddWithValue("Receipt_time", lbltime.Text)
cmd.Parameters.AddWithValue("rate", txtrate.Text.Trim())
'Con.Open()
cmd.ExecuteNonQuery()
Next
Con.Close()