Displaying Data from SQL to vb.net textbox - sql-server

I'm trying to retrieve data from sql server to vb.net textbox but i don't know what else to do all the tutorials i have are just to retrieve records from the database to datagrid view..please help..
Private Sub txtrfid_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtrfid.KeyPress
cn.Open()
With cmd
.Connection = cn
.CommandText = "SELECT * FROM Students WHERE RFID like '%" & txtrfid.Text & "%'"
End With
MsgBox("Record Found!", MsgBoxStyle.Information, "Update")
da.SelectCommand = cmd
dt.Clear()
da.Fill(dt)
cn.Close()
txtname.Text = 'Firstname'

You're populating a DataTable with the data from the database so you then have to get the data from that DataTable into the TextBox. You can do that with data binding, which is how you've probably seen it done with a grid, e.g.
txtname.DataBindings.Add("Text", dt, "Firstname")
That's definitely how you'd do it if you were retrieving multiple records that you wanted to be able to navigate, although you'd probably use a BindingSource in between. If there's only one record then you might instead just move the data manually, e.g.
txtname.Text = CStr(dt.Rows(0)("Firstname"))

If you want to display only a single value (FirstName) from Table then see following piece of code
Using conn As New SqlConnection("connstr")
conn.Open()
Dim cmd As New SqlCommand("", conn)
Dim txtName As String
cmd.CommandText = "SELECT firstname FROM Students WHERE RFID ='" & txtrfid.Text & "'"
txtName = IIf(IsDBNull(cmd.ExecuteScalar), "", cmd.ExecuteScalar)
If txtName <> "" Then
MsgBox("Record Found!", MsgBoxStyle.Information, "Update")
Textbox1.Text = ""
Textbox1.Text = txtName
else
MsgBox("No Record Found!", MsgBoxStyle.Information, "INFO.")
End If
End Using

There are many ways to retrieve the data. You can simply retrieve the data from sql database to textbox using sql data reader which is one of my favourite. Let me share to you.
Note : Don't forget to import system.data.sqlclient
Private Sub txtrfid_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtrfid.KeyPress
strConn = "Data Source=" & servernamehere & ";Initial Catalog=" & databasenamehere & ";User ID=" & userid & ";Password=" & password
sqlConn = New SqlConnection(strConn)
sqlConn.Open()
Dim sqlcmd As New SqlCommand("Your query here", sqlConn)
Dim myreader As SqlDataReader
myreader = sqlcmd.ExecuteReader()
myreader.Read()
If myreader.HasRows Then
txtrfid.Text = myreader.Item("column name from sql database table").Tostring
End If
sqlConn.Close()
End Sub
You may catch the exception with Try-Catch Technique.

Related

Refresh datagridview after inserting records into SQL Server database

I'm trying to update datagridview after inserting a new record.
The following button is located on a form and the datagridview is located on another form:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim dt As New DataTable
Using DBCon As New SqlConnection("Server=192.168.1.4,1433;Database=example;User=test;Pwd=test;"),
DBCmd As New SqlCommand("INSERT INTO Jobs (Zone,Equipement,Description)
VALUES ( '" & TextEdit1.Text & "','" & TextEdit2.Text & "','" & TextEdit3.Text & "') ", DBCon)
DBCon.Open()
dt.Load(DBCmd.ExecuteReader)
mainform.GridControl1.DataSource = dt
End Using
MsgBox.Show("Record Has been Added Successfully!!")
DialogResult = DialogResult.OK
Catch ex As Exception
MsgeBox.Show(ex.Message)
End Try
You need to write the below code. Request you to go through this link to know how to parametrize your query with CRUD demo.
dt.Load(DBCmd.ExecuteReader)
mainform.GridControl1.DataSource = dt
mainform.GridControl1.Refresh()

Visual Studio Local Database, check if boolean is true

first time poster here.. I've been struggeling with this problem for a while.
This piece of code checks if the combination of username and password exist, and if it does it redirects to a new form.
The problem is that i also wanna check if a bit value is true or false, and if it then redirect to another page aswell. I just dont know how to.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim connection As New SqlClient.SqlConnection
Dim command As New SqlClient.SqlCommand
Dim myData As SqlClient.SqlDataReader
Dim Dataset As New DataSet
Dim adaptor As New SqlClient.SqlDataAdapter
connection.ConnectionString = ("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\NewFolder1\Members.mdf;Integrated Security=True")
command.CommandText = "SELECT * FROM [User] WHERE username = '" & TextBox1.Text & "' AND password= '" & TextBox2.Text & "';"
connection.Open()
command.Connection = connection
adaptor.SelectCommand = command
adaptor.Fill(Dataset, 0)
myData = command.ExecuteReader
If Not myData.HasRows Then
TextBox1.Clear()
TextBox2.Clear()
MsgBox("Forkert login, prøv igen")
ElseIf myData.HasRows Then
Me.Hide()
LoggetInd.Show()
End If
Here is what you can do:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connection As New SqlClient.SqlConnection
Dim command As New SqlClient.SqlCommand
Dim myData As SqlClient.SqlDataReader
connection.ConnectionString = ("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\NewFolder1\Members.mdf;Integrated Security=True")
'Don't use SELECT *, call out the columns you want by name, in the order you want them
command.CommandText = "SELECT Username, Password, Bit1 FROM [User] WHERE username = '" & TextBox1.Text & "' AND password= '" & TextBox2.Text & "';"
connection.Open()
command.Connection = connection
myData = command.ExecuteReader(CommandBehavior.CloseConnection)
Dim dbUsername As String, dbPassword As String, dbBit1 As Boolean
If myData.Read Then
'Access the data in the datareader using a 0-based index
'Be careful as this requires you to know the datatype in the database
'If you have a 64bit integer stored in the database,
'you can't call GetInt32, you have to call GetInt64.
dbUsername = myData.GetString(0)
dbPassword = myData.GetString(1)
dbBit1 = myData.GetBoolean(2)
End If
'Don't forget to Close all your DataReaders
myData.Close()
If dbUsername = "" Then
TextBox1.Clear()
TextBox2.Clear()
MsgBox("Forkert login, prøv igen")
Else
If dbBit1 Then
'Redirect as needed
Else
Me.Hide()
LoggetInd.Show()
End If
End If
End Sub
Plutonix is right, you need to use a hash to encrypt/store your passwords. You also need to use SQL parameters. Your current method is an SQL injection playground, among other things.
Call Close on all your datareaders when you are done with them, if not you will have open SQL connections all over the place. When you call ExecuteReader, be sure to use CommandBehavior.CloseConnection. This closes the Connection automatically after you Close the datareader.
This will hopefully get your code working, but you do need to make additional changes for security and stability.
-E

Data from textboxes not being saved in SQL database

I am not sure if it's me or there's something wrong with my code. Whenever I try to add a new account, it is being "saved" and shown in my datagridview, however, when I check under the data set or the table data, it's not being saved (or updated). I am using Visual Studio 2013 and I just checked my Microsoft SQL version - 2012. I did what I found here and in other sites, like uncheck the "Prevent saving changes that require table re-creation"; and I also changed the "Copy to output directory to Copy if newer", oh, and I also changed the |DataDirectory| to the path of the 2 mdf files.
Sorry if I'm asking a question that was asked before. And... here's my code (this one is for change password form):
If txtNewPass.Text = txtRetyped.Text Then
Dim strSql As String
Try
Dim objAdap As SqlDataAdapter
Dim objDt As New DataTable
strConn = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FHGES.mdf;Integrated Security=True"
objConn = New SqlConnection(strConn)
Dim s As String = "SELECT * FROM tblAccounts WHERE UName COLLATE Latin1_General_CS_AS='" & frmLogin.txtUname.Text & "'AND PWord COLLATE Latin1_General_CS_AS='" & frmLogin.txtPassword.Text & "';"
objComm = New SqlCommand(s, objConn)
objAdap = New SqlDataAdapter(objComm)
objAdap.Fill(objDt)
lblUName.Text = objDt.Rows(0)(4).ToString
strSql = "UPDATE tblAccounts SET PWord='" & txtRetyped.Text & "' WHERE UName='" & lblUName.Text & "'"
objComm = New SqlCommand(strSql, objConn)
objConn.Open()
objComm.ExecuteNonQuery()
objConn.Close()
MessageBox.Show("Saved new password, please re-login", "FHGES", MessageBoxButtons.OK)
frmLogin.Show()
frmLogin.txtPassword.Clear()
frmLogin.txtPassword.Focus()
Me.Hide()
Catch ex As Exception
MsgBox(ex.Message)
Finally
If objConn.State = ConnectionState.Open Then
objConn.Close()
End If
End Try
Else
MessageBox.Show("Password don't match!", "FHGES", MessageBoxButtons.OK)
txtNewPass.Clear()
txtRetyped.Clear()
txtNewPass.Focus()
End If

How to get rid of this error: An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;'

The purpose of my application is when a user types in a customer, their username and a message into the respective textboxes, it's supposed to be recorded into a table on SQL Server after the user presses the send button.
Here's my code:
Public Class Form1
Dim Con As OleDbConnection
Dim cmd As New OleDbCommand
Dim conString As String = "Data Source=176.111.555.24;Initial Catalog=MyDatabase;User ID=Username;Password=Password"
Public Sub MessageSent()
Try
Dim con As New OleDbConnection
con.ConnectionString = conString
con.Open()
cmd.Connection = con
cmd.CommandText = "insert into tblmessage(Customer, UserName, Message) values('" & txtCustomer.Text & "', '" & txtUserName.Text & "', '" & rtfMessage.Text & "')"
cmd.ExecuteNonQuery()
con.Close()
MsgBox("Message Sent")
con.Close()
con.Dispose()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
MessageSent()
End Sub
I'm getting the following error:
An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;'.
What is it that I'm doing wrong and how can this be resolved.
It looks like you are trying to give a SQL Server connection string to an OleDbConnection. You need to either use a SqlConnection to open with that connection string or else you need to create a valid OLEDB connection string to point to that database. For reference, see this site.
When you want to connect to an MS SQL database you should use SQL connection instead of OleDbConnection.
The same is true for sqlCommand over the OldDbommand.
This SO question as some answers explaining the difference between Sql and OldDb Client.
Public Sub MessageSent()
Try
Using con As SqlConnection = New SqlConnection
con.ConnectionString = "Data Source=176.111.555.24;Initial Catalog=MyDatabase;User ID=Username;Password=Password"
con.Open()
Using cmd As New SqlCommand
cmd.Connection = con
cmd.CommandText = "insert into tblmessage(Customer, UserName, Message) values('" & txtCustomer.Text & "', '" & txtUserName.Text & "', '" & rtfMessage.Text & "')"
cmd.ExecuteNonQuery()
End Using
MsgBox("Message Sent")
con.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I think you are just missing this bit: Provider=SQLOLEDB;
For example:
Dim conString As String = "Provider=SQLOLEDB;Data Source=176.111.555.24;Initial Catalog=MyDatabase;User ID=Username;Password=Password"

How to insert textbox values to sql server 2012 database using vb.net

i have a problem with my connection to database dont know where the exact problem is.i have to insert values of textbox to the sql server database.
here is my code:
Imports System.Data
Imports System.Data.SqlClient
Public Class lbluog
Dim myconnection As SqlConnection
Dim mycommand As SqlCommand
Dim dr As SqlDataReader
Dim dr1 As SqlDataReader
Dim ra As Integer
Private Sub btnadddata_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadddata.Click
myconnection = New SqlConnection("server=TAHIR-PC;database=myDataBase")
'you need to provide password for sql server
myconnection.Open()
mycommand = New SqlCommand("insert into tblstudentrecords([fname],[lname],[fathername],[phoneno],[address]) values ('" & txtfname.Text & "','" & txtlname.Text & "','" & txtfathername.Text & "','" & txtphoneno.Text & "','" & txtaddress.Text & "')", myconnection)
mycommand.ExecuteNonQuery()
MessageBox.Show("New Row Inserted" & ra)
myconnection.Close()
End Sub
End Class
kindly anyone help me out advance in thanx
I used your variables names mostly but cleaned up the code a little. First I declared the SqlConnection and SqlCommand with using blocks so that they will be Disposed of properly when they're finished. Second, I altered your SQL command and parameterized it. This will help you avoid SQL injection exploits. I used short form "AddWithValue" because I didn't specifically know the datatypes to declare them as they are in your database (this way should work).
Private Sub btnadddata_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadddata.Click
' Assumes your login account has permissions to the database
Using myconnection As SqlConnection = New SqlConnection("server=TAHIR-PC;database=myDataBase;trusted_connection=yes;")
myconnection.Open()
Using mycommand As SqlCommand = myconnection.CreateCommand
' Setup the SQL command with parameters. Parameters protect from SQL injection exploits (and make your SQL easier to read/manage).
mycommand.CommandText = "insert into tblstudentrecords([fname],[lname],[fathername],[phoneno],[address]) values (#fname, #lname, #farthername, #phoneno, #address)"
mycommand.Parameters.AddWithValue("#fname", txtfname.Text)
mycommand.Parameters.AddWithValue("#lname", txtlname.Text)
mycommand.Parameters.AddWithValue("#fathername", txtfathername.Text)
mycommand.Parameters.AddWithValue("#phoneno", txtphoneno.Text)
mycommand.Parameters.AddWithValue("#address", txtaddress.Text)
Dim rowsAffected As Integer = mycommand.ExecuteNonQuery()
' This would be one always in this case unless the statement failed
MessageBox.Show("Rows inserted: " & rowsAffected)
End Using
myconnection.Close()
End Using
End Sub
If you're having a connection issue you should post the specific Exception text (or any other Exception text you're receiving).

Resources