Input Data into SQL Server using Visual Studio 2012 (VisualBasic) - sql

I am trying to create a simple form for users to input data to book a course. They fill in the textboxes and press submit, and it needs to send an email to me with the information (I have this working) and it also needs to add it to a database (this is what I am struggling with). I also really need to understand the code so I can use it again in future.
I am making a new database/form just to get this working, then I will implement it to my working form that sends email as well.
Currently I have created a database with one table, containing: ID, Name, Course Name and Address
I have created a form with 3 text boxes (txtName, txtCourseName and txtAddress) with a submit button, but from here I am not sure how to make it so I put values in the textboxes, click the submit button and they are added to the database. Any help would be great, thanks.
Fred

Just create 3 textboxes and 1 button on the form copy all this code, dont forget to name the textboxes accordingly
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Dim Con As OleDbConnection
Dim cmd As New OleDbCommand
Dim conString As String = "This part you have to do it your self you can go to this link to check whick string works for u http://www.connectionstrings.com/"
Public Sub CourseSave()
Try
Dim con As New OleDbConnection
con.ConnectionString = conString
con.Open()
cmd.Connection = con
cmd.CommandText = "insert into tablename(Name, [Course Name], Address) values('" & Me.txtName.Text & "', '" & Me.txtCourseName.Text & "', '" & Me.txtAddress.Text & "')"
cmd.ExecuteNonQuery()
con.Close()
MsgBox("New Course Saved")
con.Close()
con.Dispose()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
CourseSave()
End Sub
End Class
if you still get errors post me the error I might be able to help you.

If you are comfortable with adding a dataset to your project,
(Right Click Project > Add > New Item > Data > Dataset)
Add a Table Adapter and build a SQL Select statement similar to the one below using Query Builder (which will also create your INSERT statement)
Select txtName, txtCourseName , txtAddress From MyTable
You can then call the Insert statement from your button code, along the lines of...
Dim sta As New YourDataTableAdapter.TableAdapter
sta.Insert(txtName, txtCourseName , txtAddress)
sta.Dispose()
http://msdn.microsoft.com/en-us/library/6sb6kb28.aspx

Related

How to delete a row in sql using vb.net

Sorry if its easy or basic i am brand new to sql and tables so im just trying to figure it out
Basically im trying to delete a row that the user selects
By having them click on a row then clicking a delete button but i don't know how that should look ive tried a few different ways but none of them seem to work.
No error comes up but it just dosen't delete the row
Private Sub DeleteSelectedUsers()
Dim connection As SqlConnection = New SqlConnection()
connection.ConnectionString = "Data Source=GERARD-PC\SQLEXPRESS; Initial Catalog=TestDB;User ID=AccountsUser;Password=password123"
connection.Open()
Dim adp As SqlDataAdapter = New SqlDataAdapter _
("Delete * from dgrdUsers.SelectedRows(0).Cells", connection)
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
Dim username As String = dgrdUsers.SelectedRows(0).Cells.Item("Username").Value.ToString()
If (MessageBox.Show(Me, "Do you want to delete user " & username & "?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes) Then
DeleteSelectedUsers()
End If
Catch ex As Exception
End Try
End Sub
Any ideas?
The syntax required to delete a row in the database table requires at least three parts.
The DELETE command
The FROM statement to identify the table where the delete action should occur
The WHERE condition to identify the record (or records) to delete
So it is a string like this: DELETE FROM tablename WHERE condition
and applied to your code you get this.
Private Sub DeleteSelectedUsers(userName as String)
Using connection As SqlConnection = New SqlConnection()
connection.ConnectionString = "...."
connection.Open()
Dim cmd As SqlCommand = New SqlCommand _
("DELETE FROM Table WHERE userName = #user", connection)
cmd.Parameters.Add("#user", SqlDbType.NVarChar).Value = userName
cmd.ExecuteNonQuery()
End Using
End Sub
(Table and UserName are fantasy names because we don't know what is the actual schema of your database)
Other things I have changed:
The connection is created inside a using block to be sure a proper
closure and dispose happens even in case of errors
The name of the user to remove should be passed as parameter to the
function
No need to use an adapter when you just need to execute a single
SqlCommand
The query doesn't concatenate strings to build the command but use a
parameter added to the command itself and specifying a type for the
data matching the type on the database table

'Fill: SelectCommand.Connection property has not been initialized.'

I am using a visual studio 2022 vb.net and mssql management studio.
login form
Private Sub Btnlogin_Click(sender As Object, e As EventArgs) Handles Btnlogin.Click
cn.Open()
cm = New SqlClient.SqlCommand("select * from table_user where username like '" & username.Text & "' and password like '" & password.Text & "'and usertype= '" & usertype.SelectedItem & "'", cn)
dr = cm.ExecuteReader
sda.Fill(dt)
If (dt.Rows.Count > 0) Then
MessageBox.Show("You are login as " + dt.Rows(0)(2))
If (usertype.SelectedIndex = 0) Then
Dim a As New dashboard
a.Show()
Me.Hide()
Else
Dim b As New Admin
b.Show()
Me.Hide()
End If
Else
MessageBox.Show("Username or Password Incorrect. CONTACT ADMINISTRATOR!")
End If
cn.Close()
End Sub
Module
Imports System.Data.SqlClient
Module Module1
Public cn As New SqlConnection("Data Source=DESKTOP-7POF5HE\SQLEXPRESS;Initial Catalog=dict;Integrated Security=True")
Public cm As New SqlCommand
Public dr As SqlDataReader
Public sda As SqlDataAdapter = New SqlDataAdapter(cm)
Public dt As DataTable = New DataTable()
End Module
CAN YOU HELP ME TO SOLVE THIS?
Seems there are several issues with this code.
In your module, you create the command object and the data adapter object. But in the form method, you create a new command object. But that will not update the data adapter to use that new command object. Class variables are reference types. They just point to an object in the memory somewhere. Your cm variable will point to the new command object, but your sda object will internally still point to the old command object.
Furthermore:
You are using both a data reader and a data adapter. Both have their pros and cons, but you probably don't need (or want) to use them both at the same time. I assume you want to use the data adapter. So you can drop the dr = cm.ExecuteReader line in the form method.
Since you will probably always want to create command objects and data adapter objects on the fly (as I would), you could remove them from the module. Just create them both as local variables in your form method.
Try to use the Using statement for such objects. They need to be disposed of nicely when the form method finishes. Otherwise they might keep valuable system resources in use until the .NET garbage collector disposes them (which will probably occur when you close your application, not earlier).
Also be careful with concatenating SQL statements from variables. What would happen here if you enter this text in your username textbox?: ';delete from table_user;--
Hint: Do not actually try it! It will try to delete all your users from the database table table_user. Just try to manually reproduce the SQL string that will be built in your form method. This is called an SQL injection attack. To avoid such nasty things, it's easiest to use SQL parameters in your SQL statements and pass them separately to your command object.

Is paging in DataGridView possible?

Is paging in DataGridView possible in VB.NET?
I've successfully connected to a database and is able to import the data into the DataGrid, but the problem is that the table i have is huge with over 10mil rows. So showing in all in one view is either slowing down the loading time, or if i choose to add more columns of data the application will turn out to be an error.
For example, this line would work
cmd.CommandText = "SELECT primaryTitle, startYear, runtimeMinutes, genres, FROM Basics"
but this line would throw me an error called System.OutOfMemoryException
cmd.CommandText = "SELECT primaryTitle, startYear, runtimeMinutes, genres, directors, writers FROM Basics, Crew"
Any help would be appreciated.
This is my current code. The only thing i've done is importing the data into the DataGridView, nothing more since i can't proceed anymore.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlClient.SqlConnection
con.ConnectionString = "Data Source=DESKTOP-7SOUE1N\SQLEXPRESS;Initial Catalog=IMDb MOVIE DATABASE SYSTEM;Integrated Security=True"
con.Open()
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = con
cmd.CommandText = "SELECT primaryTitle, startYear, runtimeMinutes, genres, directors, writers FROM Basics, Crew"
Dim rdr As SqlClient.SqlDataReader = cmd.ExecuteReader
Dim dt As New DataTable
dt.Load(rdr)
rdr.Close()
DataGridView1.DataSource = dt
con.Close()
End Sub
End Class
Yes, certainly is. This is how I usually do it.
Prerequisities:
DataGridView DataGridView1
ToolStrip ToolStrip1
TextBox PageNo
Label PageCount
Button btnPageBack
Button btnPageNext
Label TotalShown
Label OutOfTotalRecords
(some labels like "Page", " from ", "Total shown ", " out of ", " records")
Dim RowsPerPage as Int16 = 40 ' set
This is how the ToolStrip bellow DataGridView footer looks in designer:
Fetching or updating the list SQL (wrapped in LoadListOfRecords() sub):
"SELECT
...
ORDER BY " & dgwSortCol & " " & dgwSortOrder & " " &
OFFSET " & ((IIf(Me.PageNo.Text = "", 1, CInt(Me.PageNo.Text)) - 1) * RowsPerPage) & "
ROWS FETCH NEXT " & RowsPerPage & " ROWS ONLY; "
You might skip ORDER at first. But notice OFFSET xx ROWS, which tells where in database it should start to read records (by how many records to offset it from beginning) and FETCH NEXT xx ROWS ONLY, which tells how many rows to read and load to a "page". I skipped stuff like creating DataSet, reading DataTable, assigning it to DataGridView's DataSource and such.
Button Back (I won't put Next, it's nearly identical, just changed limiting condition and iteration):
Private Sub btnPageBack_Click(sender As System.Object, e As System.EventArgs) Handles btnPageBack.Click
If CInt(Me.PageNo.Text) > 1 Then
Me.PageNo.Text = CInt(Me.PageNo.Text) - 1
End If
Call LoadListOfRecords()
End Sub
Manual entry of page number (go to particular page), following Enter key stroke:
Private Sub PageNo_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles PageNo.KeyDown
Call LoadListOfRecords()
End Sub
And that's about it. Simple, easy to use by users, works as charm, proven by time. No clutter of 3rd party controls and libraries.

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

Fill DataGridView with data from SQL

I want to fill a DataGridView with data returned from a SQL. So here is my code [I provided cause some people may think I'm asking for help before trying myself]
I want the DataGridView to be filled by a data from SQL not to show all the records.
The SQL "Select * From books where title='php%' Order By Title;"
useless code :( :'( :<
Imports System.Data
Imports System.Data.SqlClient
Public Class frmMain
Dim connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database.mdb;Persist" & " Security Info=True"
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.BooksTableAdapter.Fill(Me.TblBooks.books)
End Sub
Private Sub txtTerm_TextChanged() Handles txtTerm.TextChanged
If Trim(txtTerm.Text) = "" Then Exit Sub
Dim tblCustomBooks As New DataTable
Dim adpBooks As New OleDb.OleDbDataAdapter("Select * From books where title='php%' Order By Title", _
'"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database.mdb;Persist" & " Security Info=True")
adpBooks.Fill(tblCustomBooks)
BooksTableAdapter.Fill(tblCustomBooks)
'Dim myConnection As SqlConnection
'Dim myCommand As SqlDataAdapter
'myConnection = New SqlConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database.mdb;Persist" & " Security Info=True")
'myCommand = New SqlDataAdapter("Select * From books where title='php%' Order By Title", myConnection)
'Dim ds As DataSet = New DataSet()
'myCommand.Fill(ds)
'gridTable.DataSource = ds
End Sub
Looks like you've tried a number of different things, but it's not apparent from your code what order you tried them in. Based on the current version of your code, you're missing two things:
First, an OleDBConnection object to use with the OleDbDataAdapter.
Second, you're not assigning anything to the DataGridViews DataSource property, so nothing will show up.
Also, you appear to be using two different OleDbDataAdapters (or maybe two different DataAdapters altogether) to fill tblCustomBooks, so depending on what BooksTableAdapter is set up as may also be causing you problems.
Try this:
Private Sub txtTerm_TextChanged() Handles txtTerm.Changed
If Trim(txtTerm.Text) = "" Then Exit Sub
Dim tblCustomBooks As New DataTable
Using conn As New OleDbConnection(connectionString)
Dim adpBooks As New OleDbDataAdapter("SELECT * FROM books WHERE title = 'php%' ORDER BY title", conn)
adpBooks.Fill(tblCustomBooks)
gridTable.DataSource = tblCustomBooks
End Using
End Sub
See:
DataGridView.DataSource Property
OleDbDataAdapter Class
In your SQL statement try [WHERE Title LIKE 'php%'] instead of [WHERE Title = 'php%'].
I've run into similar problems with MS SQL and this was the fix. I'm not sure if the SQL syntax is the same for the Jet provider, but it's worth a try at least.
HTH
dim dt as new datatable
'i already maked the class and now load from a database
dt=cls.getdata("select * from tblinf")
datagridview1.datasource=dt