fetching single value form database in vb.net - vb.net

this my database table
id name
1   abc
2    xyz
it i enter 1 then respective value "abc" display in different text box???
Private Sub butsea_Click(sender As Object, e As EventArgs) Handles butsea.Click
Dim dset As New DataSet
Dim da As SqlDataAdapter
Dim myCmd As New SqlCommand
Try
myConn.ConnectionString = "Data Source=THEONE\PARTH;Initial Catalog=testdatabase;Integrated Security=True;"
myConn.Open()
Dim avalue As String = (InputBox("Input Student Id", "Search Student")).ToString
txt_id.Text = avalue
da = New SqlDataAdapter("SELECT * FROM studentdetails where student_id= '" & txt_id.Text & "", myConn)
If dset.Tables(0).Rows.Count > 0 Then
'what should i write here
Else
MsgBox("No Record Found")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
myConn.Close()
End Try
End Sub

If you need to fetch just a single value - using DataAdapter and DataSet is overkill. Use SqlCommand.ExecuteScalar method and in your query instead of "SELECT * ..." do a "SELECT YOURFIELD ... ".
this way you don't have to jump thru hoops building a dataset, checking number of rows etc. and just check returned value for Nothing instead.
UPDATE Here is your code modified to use ExecuteScalar
Private Sub butsea_Click(sender As Object, e As EventArgs) Handles butsea.Click
Dim myCmd As SqlCommand
Dim myConn As New SqlConnection
Dim oResult As Object
Try
myConn.ConnectionString = "Data Source=THEONE\PARTH;Initial Catalog=testdatabase;Integrated Security=True;"
myConn.Open()
Dim avalue As String = (InputBox("Input Student Id", "Search Student")).ToString
txt_id.Text = avalue
myCmd = New SqlCommand("SELECT student_name FROM studentdetails where student_id= '" & txt_id.Text & "'", myConn)
oResult = myCmd.ExecuteScalar()
If oResult IsNot Nothing Then
txt_name.text = oResult.ToString
Else
MsgBox("No Record Found")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
myConn.Close()
End Try
End Sub
This code assumes that database field that u need to display is called student_name and that you added TextBox called txt_name to your form.

You need to add other textboxes for every field you want to show.
(For example a textbox called txtStudentName could be used for the name, and so on for other fields present in the table studentdetails).
The correct way to query your database (leaving out other methods like using a SqlDataReader) should be the following
Dim dset As New DataSet
Dim da As SqlDataAdapter
Try
myConn.ConnectionString = "Data Source=THEONE\PARTH;Initial Catalog=testdatabase;Integrated Security=True;"
myConn.Open()
Dim avalue As String = (InputBox("Input Student Id", "Search Student")).ToString
txt_id.Text = avalue
' prepare the adapter with a commandtext. Do not use string concatenation from user input'
da = New SqlDataAdapter("SELECT * FROM studentdetails where student_id=#id", myConn)
da.SelectCommand.Parameters.AddWithValue("#id", txt_id.Text)
' Fill the dataset'
da.Fill(dset)
If dset.Tables(0).Rows.Count > 0 Then
' Supposing you have a field for the studentname in the first column of the returned
' datatable rows(rowindex)(columnindex)
txtStudentName.Txt = dset.Tables(0).Rows(0)(0).ToString()
.....
' Set the text property of other textboxes for other fields to show'
Else
MsgBox("No Record Found")
End If

Related

Database locked in vb.net when trying to update data in vb.net

Hello I have a simple method to update customer details in one of my database tables however when i try to update it an error occurs saying the database is locked. I have no idea how to fix this because my add and delete queries work just fine.
This is the error message:
System.Data.SQLite.SQLiteException: 'database is locked
database is locked'
Public Sub updateguest(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN UPDATED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Dim usql As String = "UPDATE Customers SET fname = '" & txtFName.Text & "'" & "WHERE CustomerID ='" & txtSearchID.Text & "'"
updateguest(usql)
End Sub
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
Dim sSQL As String
Dim newds As New DataSet
Dim newdt As New DataTable
Dim msql, msql1 As String
Dim con As New SQLiteConnection(ConnectionString)
con.Open()
msql = "SELECT * FROM Customers Where Fname Like '" & txtSearchName.Text & "%'"
msql1 = "SELECT * FROM Customers Where CustomerID '" & txtSearchID.Text & "'"
Dim cmd As New SQLiteCommand(msql, con)
Dim cmd1 As New SQLiteCommand(msql1, con)
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
Dim mdr As SQLiteDataReader = cmd.ExecuteReader()
If mdr.Read() Then
If txtSearchName.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE fname LIKE'" & txtSearchName.Text & "%'"
Dim con1 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con1)
con1.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con1.Close()
txtSearchID.Clear()
ElseIf txtSearchID.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE CustomerID ='" & txtSearchID.Text & "'"
Dim con2 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con2)
con2.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con2.Close()
txtSearchName.Clear()
End If
Else
MsgBox("No data found")
End If
End Sub
Private Sub IbtnDelete_Click(sender As Object, e As EventArgs) Handles ibtnDelete.Click
Dim dsql As String = "DELETE FROM customers WHERE customerid = " & txtSearchID.Text & ""
deleteme(dsql)
updatedgv(dgvCustomerInfo)
txtSearchID.Clear()
txtSearchName.Clear()
End Sub
Public Sub deleteme(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN DELTED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN DELTED!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
You made a good start on keeping your database code separate from you user interface code. However, any message boxes should be shown in the user interface and any sql statements should be written in the data access code.
I used Using...End Using blocks to ensure that database objects are closed and disposed. I used parameters to protect against sql injection. I am not too sure of the mapping of DbType types to Sqlite types. You might have to fool with that a bit. In you original Update statement you had the ID value in quotes. This would pass a string. When you use parameters, you don't have to worry about that or ampersands and double quotes. Just one clean string.
Private ConStr As String = "Your connection string"
Public Function updateguest(FirstName As String, ID As Integer) As Integer
Dim Result As Integer
Dim usql As String = "UPDATE Customers SET fname = #fname WHERE CustomerID = #ID;"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(usql, con)
cmd.Parameters.Add("#fname", DbType.String).Value = FirstName
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
con.Open()
Result = cmd.ExecuteNonQuery
End Using
Return Result
End Function
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Try
Dim Result = updateguest(txtFName.Text, CInt(txtSearchID.Text))
If Result > 0 Then
MsgBox("New RECORD HAS BEEN UPDATED!")
Else
MsgBox("NO RECORD HAS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Insert Into data from other table vb . net access OleDb

I have different tables on same database , and i need to insert ID's of data from combobox.
Here's client table
what i need is to get id from combobox selected item and put it on the final table,
this is what i try
cmd.Parameters.AddWithValue("Client", client.Text)
Private Sub livbtn_Click(sender As Object, e As EventArgs) Handles livbtn.Click
'ModePaiement()
Try
SQL = "INSERT INTO LIVRAISONCLIENTGNC(Codeclient) SELECT code_client from client WHERE client = #Client "
Execute(SQL, "Insert")
MessageBox.Show("The record has been saved.", "",
MessageBoxButtons.OK, MessageBoxIcon.Information)
ResetMe()
Catch ex As Exception
MessageBox.Show("" & ex.Message, "",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End Sub
and not working for sure , please help !
here's Module data connection:
Option Explicit On
Option Strict On
Imports System.Data.OleDb
Module AccessDB_Connection
Public Function GetConnectionString() As String
Dim strCon As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data source=" & Application.StartupPath & "\BLdatabase.accdb;Persist Security Info = false;"
Return strCon
End Function
Public con As New OleDbConnection(GetConnectionString())
Public cmd As OleDbCommand
Public SQL As String = String.Empty
Public Function PerformCRUD(Com As OleDbCommand) As DataTable
Dim da As OleDbDataAdapter
Dim dt As New DataTable()
Try
da = New OleDbDataAdapter
da.SelectCommand = Com
da.Fill(dt)
Return dt
Catch ex As Exception
MessageBox.Show("" & ex.Message)
End Try
Return dt
End Function
End Module
thank's everybody for replying;
so here's execute method :
Private Sub Execute(MySQL As String, Optional Parameter As String = "")
cmd = New OleDbCommand(MySQL, con)
AddParameters(Parameter)
PerformCRUD(cmd)
End Sub
Private Sub AddParameters(str As String)
cmd.Parameters.AddWithValue("Client", client.Text)
End Sub
Public Function PerformCRUD(Com As OleDbCommand) As DataTable
Dim da As OleDbDataAdapter
Dim dt As New DataTable()
Try
da = New OleDbDataAdapter
da.SelectCommand = Com
da.Fill(dt)
Return dt
Catch ex As Exception
MessageBox.Show("" & ex.Message)
End Try
Return dt
End Function
so it's very simple , i need to store an id value from an selected item :
enter image description here
here's an example , i need to store that value 26 from that table client to other table when i select IMAX client from combobox
enter image description here
enter image description here
there's 2 different results it depends on the query used :
with SQL = "INSERT INTO LIVRAISONCLIENTGNC(Codeclient) SELECT code_client from client WHERE client = #Client " --> there's nothing happened
with SQL = "INSERT INTO LIVRAISONCLIENTGNC(Codeclient) values(SELECT code_client from client WHERE client = #Client) "
--> error
enter image description here
The issue I see, you are trying to run:
SQL = "INSERT INTO LIVRAISONCLIENTGNC(Codeclient) SELECT code_client from client WHERE client = #Client "
However, in your PerformCRUD method, you are filling a data adapter and returning a DataTable based on an INSERT where ExecuteNoQuery is the method to use.
Here is an example (More Info):
Using cmd = con.CreateCommand()
cmd.CommandText = SQL
'It is good practice to specify the data type. Note: 80 in this example is the column size/length.
cmd.Parameter.Add("#Client", OleDbType.VarChar, 80).Value = client.Text
cmd.Connection = con
con.Open() 'if not already open
cmd.ExecuteNonQuery()
End Using

how to display data in text box in vb.net using sql

Private Sub BtnReturn_Click(sender As Object, e As EventArgs) Handles btnReturn.Click
If BorrowAccession.Text = "" Or txtBorrowerstype.Text = "" Then
MsgBox("All fields are required.", MsgBoxStyle.Exclamation)
ElseIf txtremarks.Text = "Over Due" Then
sql = "Select * From `maintenance` fine ='" & txtfine.Text & "' "
reloadtxt(sql)
End sub
how will i display the fine in txtfine.text from my maintenance database after it satisfy the condition from txtremarks. i tried some youtube tutorials but only displaying it from data grid .. want i basically want is directly display it from database to textbox. btw im newbie in vb programming thank you in advance
for my reloadtxt this is the code.
Public Sub reloadtxt(ByVal sql As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sql
End With
dt = New DataTable
da = New MySqlDataAdapter(sql, con)
da.Fill(dt)
Catch ex As Exception
' MsgBox(ex.Message & "reloadtxt")
Finally
con.Close()
da.Dispose()
End Try
End Sub
To populate an object with data from a database you need to access the objects text property.
Textbox1.Text = "Some Text, static or dynamic"
Since you are pulling the data from a datatable you would access the column named "fine" and put that value in the textbox.text property.
Textbox1.Text = dt.row(0).item("fine").tostring
Changed Or to OrElse because it short circuits the If and doesn't have to check the second condition if the first condition is True.
In the reloadtxt method you filled a DataTable and did nothing with it. I changed it to a Function that returns the DataTable. The connection and command are now included in a Using...End Using block so they are closed and disposed even if there is an error.
Never concatenate strings to build an sql statement. Always used parameters.
Private Sub BtnReturn_Click(sender As Object, e As EventArgs) Handles btnReturn.Click
If BorrowAccession.Text = "" OrElse txtBorrowerstype.Text = "" Then
MsgBox("All fields are required.", MsgBoxStyle.Exclamation)
ElseIf txtremarks.Text = "Over Due" Then
Dim dt = reloadtxt()
DataGridView1.DataSource = dt
End If
End Sub
Public Function reloadtxt() As DataTable
Dim dt As New DataTable
Using con As New MySqlConnection("Your connection string"),
cmd As New MySqlCommand("Select * From maintenance Where fine = #Fine", con)
cmd.Parameters.Add(#Fine, MySqlDbType.VarChar, 50).Value = txtfine.Text
Try
con.Open()
dt.Load(cmd.ExecuteReader)
Catch ex As Exception
MsgBox(ex.Message & "reloadtxt")
End Try
End Using
Return dt
End Function

How do i make padleft work with the below code. I want to do search with out leading zero

With the below code I can pull info with zero in the front. I am trying to eliminate entering zero for instance 789136 for 0789136. Please advise
Private Sub BtnSearch_Click(sender As System.Object, e As System.EventArgs) Handles BtnSearch.Click
Dim connection As New SqlConnection("DATABASE CONNECTION")
Dim Table As New DataSet
Dim ZeroFill As String
If TxtBoxW1.Text = "" Then
ZeroFill = TxtBoxW1.Text.Trim
ZeroFill = ZeroFill.PadLeft(4, "0")
MsgBox(" Please Enter a valid number", MessageBoxButtons.OK)
TxtBoxW1.Focus()
connection.Open()
Else
adapter = New SqlDataAdapter("Select * From TABLENAME where COLNAME = '" & TxtBoxW1.Text.Trim & "'", connection)
Command = New SqlCommandBuilder(adapter)
ds1 = New DataSet()
adapter.Fill(ds1, "TABLENAME")
DataGridView1.DataSource = ds1.Tables("TABLENAME")
End If
connection.Close()
End Sub
your code does not make sense in many was. I'm not even sure what do you really need with those leading zeros.
1) Removing leading zeros
Dim Value As String = "0789136"
Dim ValueWithoutLeadingZeros As String = Value.TrimStart("0"c)
2) Other incinsistencies
Your if statement tests for empty string in TxtBoxW1. So there's no reason to read this
ZeroFill = TxtBoxW1.Text.Trim
ZeroFill = ZeroFill.PadLeft(4, "0")
since it will allways result in
ZeroFill = "0000"
and you're not using this value anyway.
Your connection.open and connection.close shoudl be all in the Else section, since you're not using it in if section. But this might be code cleanup consequence.
You should use parameters instead of direct query. Current version is risky for SQL Injection.
You shoudl use Using for Disposable objects.
3) Guessed version
I guess you want to trim leading zeros for validation, but pad your value with zeros for SQL search. In that case, your code should look somehow like this:
If TxtBoxW1.Text.Trim(" "c, "0"c).Length = 0 Then
MsgBox(" Please Enter a valid number", MessageBoxButtons.OK)
TxtBoxW1.Focus()
Else
Dim DS As New DataSet
Using Conn As New SqlConnection("DATABASE CONNECTION"), DA As New SqlDataAdapter("Select * From TABLENAME where COLNAME = #Param", Conn)
DA.SelectCommand.Parameters.Add(New SqlParameter("#Param", TxtBoxW1.Text.Trim.PadLeft(4, "0")))
Conn.Open()
DA.Fill(DS, "TABLENAME")
DataGridView1.DataSource = DS.Tables("TABLENAME")
End Using 'This will close the Connection for you
End If
My working code below:
Private Sub BtnSearch_Click(sender As System.Object, e As System.EventArgs) Handles BtnSearch.Click
SqlSelect = ""
sqlwhere = ""
expsql = sqlfrom & sqlwhere
Dim connection As New SqlConnection("database connection")
' Dim Command As New SqlCommand("Select * from table name where col1=#col1 = '" & TxtBoxW1.Text & "'", connection)
Dim Table As New DataSet
Dim sql As New SqlConnection
Dim ZeroFill As String
Dim ds as DataSet
connection.Open()
If TxtBoxW1.Text <> "" Then
ZeroFill = TxtBoxW1.Text.Trim
ZeroFill = ZeroFill.PadLeft(4, "0")
sqlwhere = ZeroFill
' MsgBox(" Please Enter a valid number", MessageBoxButtons.OK)
TxtBoxW1.Focus()
End If
adapter = New SqlDataAdapter("Select * From table name where col1 = " & sqlwhere & "", connection)
'adapter = New SqlDataAdapter(Sql, connection)
Command = New SqlCommandBuilder(adapter)
ds = New DataSet()
Try
adapter.Fill(ds, "Table Name")
DataGridView1.DataSource = ds1.Tables("Table Name")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
connection.Close()
End Sub

Filling a combobox using a query with a where command (VB.NET)

I have problems with filling a combobox.
I'm able to fill one whith a simple select query.
Now I want to fill a combobox with a query that inculdes a where command. I tried several solutions but none of them worked.
How can I fill a combobox with a query with a where statement?
My code so far is:
Public Function vulComboboxTesten(box As ComboBox, naam As String) As ComboBox
box.Items.Clear()
box.Items.Add(" ")
Dim query As String
query = "Select Sector from Onderaannemers where Naam_firma = #naam "
Debug.WriteLine(query)
Dim command As OleDbCommand
command = New OleDbCommand(query, connectie)
command.Connection.Open()
Dim datareader As OleDbDataReader
datareader = command.ExecuteReader
While datareader.Read
Dim item As New ComboBoxItem
item.Content = datareader("Sector")
box.Items.Add(item)
End While
command.Connection.Close()
Return box
End Function
Try this sir. i dont know how to translate my code into your type of coding. But just read the explanations.
Private Sub StoringDatainCombobox()
Try
Dim comboSource As New Dictionary(Of String, String)()
mkcon() 'this is just my sqlCon.Open
Dim cmd As New SqlCommand
Dim rd As SqlDataReader
cmd.Connection = sqlCon
cmd.CommandText = "data_get" 'my query stored procedure.
'cotains something like this select * from tb1 where isactive = true
cmd.CommandType = CommandType.StoredProcedure
comboSource.Add(0, "") ' for blank item in the 1st value of combobox
ComboBox1.DataSource = New BindingSource(comboSource, Nothing)
ComboBox1.DisplayMember = "Value"
ComboBox1.ValueMember = "key"
ComboBox1.Text = ""
rd = cmd.ExecuteReader
While (rd.Read)
comboSource.Add(rd("dataId"), rd("dataName"))
ComboBox1.DataSource = New BindingSource(comboSource, Nothing)
ComboBox1.DisplayMember = "Value"
ComboBox1.ValueMember = "key"
ComboBox1.Text = ""
End While
sqlCon.Close()
Catch ex As Exception
MessageBox.Show("Failed." & ex.Message, "Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
You can now display the data result of your query also with an id.
if you need how to get the id when user select an item in combobox just inform me.
Hope this will help you.