Syntax error (comma) in query expression? - vb.net

Sooo I'm currently coding this second year project that I have about some library system. Just wanted to ask reallll quick if anyone could respond to this question reall fast. In a part of my coding, under my btnUpdate_Click where obviously is functioned to update the information the books in the Books table. I got an error msg when executing the program where it says Syntax error (comma) in query expression. Here's my code :
Imports System.Data.OleDb
Public Class BookDetails
Dim conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\msi\\Desktop\\UITM\\DIPLOMA CS110\\SEM 3\\CSC301\\groupproject\\ReadObrite\\ReadObrite\\User.accdb")
Dim dt As New DataTable
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter(cmd)
Public Sub view()
conn.Open()
cmd.CommandType = CommandType.Text
da = New OleDbDataAdapter("Select * from Books ", conn)
da.Fill(dt)
DataGridView1.DataSource = dt
conn.Close()
End Sub
Private Sub BookDetails_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'UserDataSet.Books' table. You can move, or remove it, as needed.
Me.BooksTableAdapter.Fill(Me.UserDataSet.Books)
conn.Open()
cmd.CommandType = CommandType.Text
da = New OleDbDataAdapter("Select * from Books ", conn)
da.Fill(dt)
DataGridView1.DataSource = dt
conn.Close()
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
cmd = conn.CreateCommand()
conn.Open()
cmd.CommandType = CommandType.Text
cmd.CommandText = "Update Books set ISBN = '" + TextBox12.Text + "' where Ttile = '" + TextBox11.Text + "', Author = '" + TextBox10.Text + "', Production = '" + TextBox9.Text + "', Category = '" + TextBox8.Text + "' and Year = '" + TextBox7.Text + "'"
cmd.ExecuteNonQuery()
conn.Close()
btnSearch_Click(New Object, New EventArgs())
view()
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Me.BooksBindingSource.RemoveCurrent()
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
cmd = conn.CreateCommand()
conn.Open()
cmd.CommandType = CommandType.Text
cmd.CommandText = "Insert into Books values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "')"
cmd.ExecuteNonQuery()
MsgBox("New book is added")
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
conn.Close()
conn.Open()
cmd.CommandType = CommandType.Text
da = New OleDbDataAdapter("Select * from Books ", conn)
da.Fill(dt)
DataGridView1.DataSource = dt
conn.Close()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
TextBox12.Text = DataGridView1.SelectedRows(0).Cells(0).Value.ToString()
TextBox11.Text = DataGridView1.SelectedRows(0).Cells(1).Value.ToString()
TextBox10.Text = DataGridView1.SelectedRows(0).Cells(2).Value.ToString()
TextBox9.Text = DataGridView1.SelectedRows(0).Cells(3).Value.ToString()
TextBox8.Text = DataGridView1.SelectedRows(0).Cells(4).Value.ToString()
TextBox7.Text = DataGridView1.SelectedRows(0).Cells(5).Value.ToString()
End Sub
Private Sub refresh()
If txtSearch.Text = "" Then
view()
End If
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
cmd = conn.CreateCommand()
conn.Open()
cmd.CommandType = CommandType.Text
cmd.CommandText = "Select * From Books Where ISBN = '" + txtSearch.Text + "' or Title = '" + txtSearch.Text + "' "
cmd.ExecuteNonQuery()
da = New OleDbDataAdapter(cmd)
dt = New DataTable
da.Fill(dt)
DataGridView1.DataSource = dt
conn.Close()
refresh()
End Sub
End Class
I tried changing all the commas to 'And'. but then a new error occured.

try this :
cmd.CommandText = "Update Books set ISBN = '" + TextBox12.Text + "' WHERE Ttile = '" + TextBox11.Text + "' AND Author = '" + TextBox10.Text + "' AND Production = '" + TextBox9.Text + "' AND Category = '" + TextBox8.Text + "' AND [Year] = '" + TextBox7.Text + "'"
notes :
Year is a SQL protected name so enclose with []
comma not supported in all SQL declination
as mentionned by IFrank, maybe error in "Ttile" column name - may throw an invalid column name error message
be carreful with controls text contents : clean them with TextBoxXX.Text.replace("'","'") or use parametized query

Related

Could not find installable ISAM in vb.Net

Imports System.Configuration
Imports System.Data.OleDb
Public Class Form1
Dim conn As New OleDbConnection
Dim cmd As OleDbCommand
Dim dt As New DataTable
Dim da As New OleDbDataAdapter(cmd)
Private bitmap As Bitmap
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;DataSource=C:\Users\AK\Documents\Programs\visual basic\Student Record\vbdatabase.accdb"
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Try
conn.Open()
cmd = conn.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "insert into Vbdatabase(ID,Firstname,Lastname,Fathername,Mothername,Class,Rollno,Address,Phoneno,Email)values('" + txtId.Text + "','" + txtFname.Text +
"','" + txtLname.Text + "','" + txtFather.Text + "','" + txtMother.Text + "','" + txtClass.Text + "','" + txtRoll.Text + "','" + txtAddress.Text + "','" + txtMobile.Text + "','" + txtEmail.Text + "')"
cmd.ExecuteNonQuery()
conn.Close()
MessageBox.Show(" Record Saved In Ms Access ", "Vbdatabase", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message, "Vbdatabase", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Im new to visual basic.. I would like to ask on how to fixed the problem "Could not find installable ISAM.". I used Visual Basic as programming language. I used MS access as the database. This would be my code.

How to solve the error: 'Column name or number of supplied values does not match table definition'?

I'm trying to run this code and, every time I try to add data to the DataGrid view and db, I'm getting this error:
System.Data.SqlClient.SqlException: 'Column name or number of supplied
values does not match table definition.
I've tried running it several times but it keeps bringing the same error.
This is my code:
Imports System.Data.SqlClient
Public Class Form2
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim i As Integer
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
cmd = con.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "insert into payment_details values('" + TextBox1.Text + "','" + TextBox2.Text + "', '" + TextBox3.Text + "', '" + TextBox4.Text + "', '" + TextBox5.Text + "', '" + TextBox6.Text + "', '" + TextBox7.Text + "', '" + TextBox8.Text + "', '" + TextBox9.Text + "', '" + TextBox10.Text + "')"
cmd.ExecuteNonQuery()
disp_data()
MessageBox.Show("Your data has been saved successfully!")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.Hide()
Form1.Show()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'FarmholdDataSet.payment_details' table. You can move, or remove it, as needed.
Me.Payment_detailsTableAdapter.Fill(Me.FarmholdDataSet.payment_details)
con.ConnectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Farmhold\Desktop\SYSTEM FILES\FARMHOLD\WindowsApp1\farmhold.mdf;Integrated Security=True"
If con.State = ConnectionState.Open Then
con.Close()
End If
con.Open()
disp_data()
End Sub
Public Sub disp_data()
cmd = con.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "select * from payment_details"
cmd.ExecuteNonQuery()
Dim dt As New DataTable()
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
DataGridView1.DataSource = dt
End Sub
Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs)
Try
If con.State = ConnectionState.Open Then
con.Close()
End If
con.Open()
i = Convert.ToInt32(DataGridView1.SelectedCells.Item(0).Value.ToString())
cmd = con.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "select * from payment_details where id=" & i & ""
cmd.ExecuteNonQuery()
Dim dt As New DataTable()
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
Dim dr As SqlClient.SqlDataReader
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
While dr.Read
TextBox1.Text = dr.GetString(1).ToString()
TextBox2.Text = dr.GetString(2).ToString()
TextBox3.Text = dr.GetString(3).ToString()
TextBox4.Text = dr.GetString(4).ToString()
TextBox5.Text = dr.GetString(5).ToString()
TextBox6.Text = dr.GetString(6).ToString()
TextBox7.Text = dr.GetString(7).ToString()
TextBox8.Text = dr.GetString(8).ToString()
ComboBox1.SelectedItem = dr.GetString(9).ToString()
TextBox10.Text = dr.GetString(10).ToString()
End While
Catch ex As Exception
End Try
End Sub
End Class
make sure your column count in database and insert query values should be same
or
try your query like this
cmd.CommandText = "insert into payment_details(colName1, colName2, colName3)
values ('" & textbox1.text &"','" & textbox2.text & "','" & textbox3.text & "') "
Do not declare database objects as Form level variables. They should be declared in the method where they are used so they can be properly closed and disposed. Using...End Using blocks handle this for you even if there is an error.
In your sql insert command you should always list the names of the fields that you are filling. This will help you avoid errors. I made up some field names and guessed at some datatypes and field sizes. Check your database for the real names, types and sizes. Note that not all fields are necessarily strings.
Always use parameter to avoid sql injection.
Private ConStr As String = "Your connection string"
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim sql = "Insert into payment_details (Payee, Method, CCNumber, Amount, InvoicePaid) Values (#Payee, #Method, #CCNumber, #Amount, #InvoicePaid);"
Using con As New SqlConnection(ConStr),
cmd As New SqlCommand(sql, con)
With cmd.Parameters
.Add("#Payee", SqlDbType.NVarChar, 100).Value = TextBox1.Text
.Add("#Method", SqlDbType.NVarChar, 50).Value = TextBox2.Text
.Add("#CCNumber", SqlDbType.NVarChar, 50).Value = TextBox3.Text
.Add("#Amount", SqlDbType.Decimal).Value = CDec(TextBox4.Text)
.Add("#InvoicePaid", SqlDbType.NVarChar, 70).Value = TextBox5.Text
End With
con.Open()
cmd.ExecuteNonQuery()
End Using
MessageBox.Show("Your data has been saved successfully!")
End Sub

data type mismatch criteria expression in vb.net,access while inserting

Imports System.Data.OleDb
Imports System.IO
Public Class insuranceform
Dim read As String
Dim datafile As String
Dim connstring As String
Dim cmd As New OleDbCommand
Public da As New OleDbDataAdapter
Dim str As String
Public ds As New DataSet
Public ds1 As New DataSet
Public ds2 As New DataSet
Dim myconnection As OleDbConnection = New OleDbConnection
Dim er As Integer
Private Sub insuranceform_Load(sender As Object, e As EventArgs) Handles MyBase.Load
read = "provider=microsoft.ace.oledb.12.0;data source="
datafile = "C:\Users\DELL\source\repos\HRIS SYSTEM\loginformdatabase\BLUESTREAM.accdb"
connstring = read & datafile
myconnection.ConnectionString = connstring
ds.Clear()
DateTimePicker1.Value = DateTime.Now
DateTimePicker2.Value = DateTime.Now
DateTimePicker3.Value = DateTime.Now
If myconnection.State = ConnectionState.Open Then
myconnection.Close()
End If
myconnection.Open()
er = 0
'cn.Open()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
End Sub
Private Sub Save_Click(sender As Object, e As EventArgs) Handles Button1.Click
ds.Clear()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
If er = 0 Then
Try
cmd.Connection = myconnection
cmd.CommandText = "insert into insurancedetail(Name,EmployeeID,PAN,UniversalAccountNumber,AdharNo,CurrentAddress,PermanentAddress,Landline,MartialStatus,MobileNumber,EmergencyContactNo,BloodGroup,DoyouHaveHDFCbankaccount,NameOfdependentmember_F) values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "','" & TextBox7.Text & "','" & TextBox8.Text & "','" & ComboBox2.Text & "','" & TextBox9.Text & "','" & TextBox10.Text & "','" & TextBox11.Text & "','" & ComboBox1.Text & "','" & TextBox12.Text & "')"
cmd.ExecuteNonQuery() 'if command is executed'
Dim result As Integer = MessageBox.Show("New insurance detail Added. Want To Add Another One.", "Added", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
Me.Close()
ElseIf result = DialogResult.Yes Then
ds.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
TextBox11.Clear()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
TextBox17.Clear()
TextBox18.Clear()
TextBox20.Clear()
ComboBox1.ResetText()
ComboBox2.ResetText()
ComboBox3.ResetText()
ComboBox4.ResetText()
ComboBox5.ResetText()
DateTimePicker1.ResetText()
DateTimePicker2.ResetText()
DateTimePicker3.ResetText()
str = "select * from insurancedetail"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "insurancedetail")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
'insert close
End If
'myconnection close
End Sub
Way too many Class level variables. Especially not myconnection and cmd. What in the world is er? Procedures should not do too much. Move some code off to other procedures, especially if they will be called more than once.
For database objects use Using blocks. They will ensure that your objects are closed and disposed even if there is an error. You don't appear to be using the DataAdapter so just fill a DataTable directly. It can be bound to a DataGridView.
There is no reason to fill the DataTable again before the save. You may want to refill is again after the save.
I am guessing at the datatypes in your database. You must check the database to get the correct datatypes and for string types get the size of the field. Convert your TextBox values to the correct types. I have only used a few of your fields for demonstration purposes. Make sure you add your parameters in the same order that they appear in the sql statement.
Private dt As New DataTable
Private connString As String = "provider=microsoft.ace.oledb.12.0;data source=C:\Users\DELL\source\repos\HRIS SYSTEM\loginformdatabase\BLUESTREAM.accdb"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SetDatePickerValues()
FillDataTable()
End Sub
Private Sub Save_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Using cn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Insert Into insurancedetail(Name,EmployeeID,PAN) Values(#Name, #EmployeeID, #PAN);", cn)
cmd.Parameters.Add("#Name", OleDbType.VarChar, 100).Value = TextBox1.Text
cmd.Parameters.Add("#EmployeeID", OleDbType.Integer).Value = CInt(TextBox2.Text)
cmd.Parameters.Add("#PAN", OleDbType.VarChar, 100).Value = TextBox3.Text
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
FillDataTable()
Dim result As Integer = MessageBox.Show("New insurance detail Added. Want To Add Another One.", "Added", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
Me.Close()
Else
ClearForm()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ClearForm()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
TextBox11.Clear()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
TextBox17.Clear()
TextBox18.Clear()
TextBox20.Clear()
ComboBox1.ResetText()
ComboBox2.ResetText()
ComboBox3.ResetText()
ComboBox4.ResetText()
ComboBox5.ResetText()
SetDatePickerValues()
End Sub
Private Sub FillDataTable()
Try
dt.Clear()
Using cn As New OleDbConnection(connString)
Using cmd As New OleDbCommand("Select * From insurancedetail", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub SetDatePickerValues()
DateTimePicker1.Value = DateTime.Now
DateTimePicker2.Value = DateTime.Now
DateTimePicker3.Value = DateTime.Now
End Sub

How to get count of records in a table?

Someone help me
I am working on our project and I need to check if my DB has already 20 records.
If so, then it will not accept records anymore.
I've been trying the codes below:
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim ds, ds2 As New DataSet
Dim da, da2 As OleDb.OleDbDataAdapter
Dim sql, sql1 As String
Dim int As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
con.ConnectionString = "Provider=Microsoft.jet.OLEDB.4.0; data source = |datadirectory|\Database6.mdb"
con.Open()
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts WHERE Username='" & TextBox1.Text & "'", con)
Dim sdr As OleDb.OleDbDataReader = cmd.ExecuteReader
Dim cmd1 As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts")
sql = "INSERT INTO Accounts ([Username], [Password], [FirstName], [LastName]) VALUES ('" & TextBox1.Text & "','" & TextBox2.Text & "', '" & TextBox3.Text & "','" & TextBox4.Text & "') "
sql1 = "SELECT Count([AccountID]) FROM Accounts"
cmd = New OleDb.OleDbCommand(sql, con)
cmd1 = New OleDb.OleDbCommand(sql1, con)
Convert.ToInt32(sql1)
cmd1.ExecuteScalar()
If sql1 < 20 Then
MsgBox("Cannot accept records")
ElseIf sdr.HasRows = False Then
cmd.ExecuteNonQuery()
MsgBox("Account Added")
ElseIf sdr.HasRows = True Then
MsgBox("Username is taken")
End If
con.Close()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Hide()
Form2.Show()
End Sub
End Class
But the convert code fires an error :
Input string was in incorrect format
But if I delete the convert code it gives me the error
Conversion from string "SELECT Count([AccountID]) FROM A" to type 'Double' is not valid."
Help me please.
TIA
I dont know VB all that well, this is from the top of my head. Your trying to convert your SQL text, which will never work. Try something like this:
dim result as object
result = cmd1.ExecuteScalar()
dim count as int
count = Convert.ToInt32(result)
If count < 20 Then

vb.net Data Gridview REfresh

i am having some issues updating a table that i have in a VB.net Windows Forms in VS 2012
i have setup the database from a service Data base, it just need a small amount of data stored locally
what i am trying to do when i create a new user it update the data grid view
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BDate1.Format = DateTimePickerFormat.Custom
BDate1.CustomFormat = "MM/dd/yyyy"
If fname.Text <> "" And lname.Text <> "" Then
If Not cn.State = ConnectionState.Open Then
cn.Open()
End If
' cn1.Open()
If rb1.Checked Then
gen = rb1.Text.ToString
ElseIf rb2.Checked Then
gen = rb2.Text.ToString
End If
cmd.CommandText = "INSERT INTO StudentTB (FirstName,LastName,Birthday,Avatar,Gender,Grade) values('" & fname.Text & "', '" & lname.Text & "', '" & BDate1.Text & "', '" & AvtarNM.Text & "', '" & gen & "', '" & TxtGrade.Text & "')"
Dim dt As New DataTable
dt.Load(cmd.ExecuteReader())
DataGridView1.DataSource = dt
' cmd.ExecuteNonQuery()
cn.Close()
fname.Text = ""
lname.Text = ""
the issue is that i can clear the table and reload it with button but it does not show the updated values with out closing the application then reopening it, i have tried a few thing and nothing seems to refresh the connection and or update the database. any help would help.
thanks
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
'DataGridView1.DataSource = Nothing
Database1DataSet1.StudentTB.Clear()
' Database1DataSet1.refresh()
' Dim myda As String
' cmd.Dispose()
' cmd.Connection = cn
'Me.Database1DataSet1.Clear()
Me.StudentTBTableAdapter.Fill(Me.Database1DataSet1.StudentTB)
' 'myda = New SqlDataAdapter(cmd)
End Sub
here is the full code
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlClient.SqlDataReader
Imports System.Windows.Forms
Public Class Student
Dim cn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Nate\documents\visual studio 2012\Projects\WindowsApplication9\WindowsApplication9\Database1.mdf;Integrated Security=True")
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Private dataAdapter As New SqlDataAdapter()
Dim gen As String
Dim bs As New BindingSource
Dim dt As New DataTable
Private Sub Student_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database1DataSet1.avTable' table. You can move, or remove it, as needed.
Me.AvTableTableAdapter.Fill(Me.Database1DataSet1.avTable)
'TODO: This line of code loads data into the 'Database1DataSet1.StudentTB' table. You can move, or remove it, as needed.
Me.StudentTBTableAdapter.Fill(Me.Database1DataSet1.StudentTB)
cmd.Connection = cn
Form1.Hide()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If AvTableBindingSource.Position + 1 < AvTableBindingSource.Count Then
AvTableBindingSource.MoveNext()
Button7.PerformClick()
' Otherwise, move back to the first item.
Else
AvTableBindingSource.MoveFirst()
Button7.PerformClick()
End If
' Force the form to repaint.
Me.Invalidate()
End Sub
Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
PictureBox1.Image = System.Drawing.Bitmap.FromFile(ID.Text)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BDate1.Format = DateTimePickerFormat.Custom
BDate1.CustomFormat = "MM/dd/yyyy"
If fname.Text <> "" And lname.Text <> "" Then
If Not cn.State = ConnectionState.Open Then
cn.Open()
End If
' cn1.Open()
If rb1.Checked Then
gen = rb1.Text.ToString
ElseIf rb2.Checked Then
gen = rb2.Text.ToString
End If
cmd.CommandText = "INSERT INTO StudentTB (FirstName,LastName,Birthday,Avatar,Gender,Grade) values('" & fname.Text & "', '" & lname.Text & "', '" & BDate1.Text & "', '" & AvtarNM.Text & "', '" & gen & "', '" & TxtGrade.Text & "')"
cmd.ExecuteNonQuery()
dt.Load(cmd.ExecuteReader())
bs.DataSource = dt
DataGridView1.DataSource = bs
cn.Close()
fname.Text = ""
lname.Text = ""
End If
End Sub
Private Sub genPCI()
If rb1.Checked Then
gen = rb1.Text.ToString
ElseIf rb2.Checked Then
gen = rb2.Text.ToString
End If
End Sub
Public Function ChangeFormat(ByVal dtm As DateTime, ByVal format As String) As String
Return dtm.ToString(format)
End Function
Private Sub Closestudent_Click(sender As Object, e As EventArgs) Handles Closestudent.Click
Form1.Show()
Me.Close()
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
bs.EndEdit()
dataAdapter.Update(dt)
DataGridView1.DataSource = dt
' dt.Load(Command.ExecuteReader())
'Database1DataSet1.Reset()
'DataGridView1.Columns.Clear()
' DataGridView1.DataSource = Nothing
' Me.StudentTBTableAdapter.Fill(Me.Database1DataSet1.StudentTB)
' StudentTBBindingSource.ResetBindings(True)
' Database1DataSet1.refresh()
' Dim myda As String
' cmd.Dispose()
' cmd.Connection = cn
' StudentTBBindingSource.ResetBindings(False)
'Database1DataSet1.StudentTB.Clear()
' 'myda = New SqlDataAdapter(cmd)
' DataGridView1.DataSource = Database1DataSet1.StudentTB
End Sub
End Class
You can try like this
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
bs.EndEdit()
dataadapter.Update(dt)
DataGridView1.DataSource = dt
End Sub
UPDATE
or you can use bindingdatasource and delare it on your form class
Dim bs As New BindingSource
and in datagridview .. in button1_click
Dim dt As New DataTable
dt.Load(cmd.ExecuteReader())
bs.DataSource = dt
DataGridView1.DataSource = bs
So, if updated then will show after button4_click
Datagridview1.datasource = nothing
Dataset.reset
dim cmd as new sqldataadapter
cmd = "SELECT * FROM YOUR_DATABSE", con
con.open
cmd.fill(Dataset)
datagridview1.datasource = dataset(0).defaultview
Add these code to you button insert
okay after a lot of playing around this seem to fix my issue http://msdn.microsoft.com/en-us/library/fbk67b6z.aspx well all i can say it is working no idea why but it works.
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Me.DataGridView1.DataSource = Me.StudentTBBindingSource
GetData("select * from StudentTB")
End Sub
Private Sub GetData(ByVal selectCommand As String)
Try
' Specify a connection string. Replace the given value with a
' valid connection string for a Northwind SQL Server sample
' database accessible to your system.
Dim connectionString As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Nate\documents\visual studio 2012\Projects\WindowsApplication9\WindowsApplication9\Database1.mdf;Integrated Security=True"
' Create a new data adapter based on the specified query.
Me.dataAdapter = New SqlDataAdapter(selectCommand, connectionString)
' Create a command builder to generate SQL update, insert, and
' delete commands based on selectCommand. These are used to
' update the database.
Dim commandBuilder As New SqlCommandBuilder(Me.dataAdapter)
' Populate a new data table and bind it to the BindingSource.
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.StudentTBBindingSource.DataSource = table
' Resize the DataGridView columns to fit the newly loaded content.
' Me.DataGridView1.AutoResizeColumns( _
' DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader)
Catch ex As SqlException
MessageBox.Show("To run this example, replace the value of the " + _
"connectionString variable with a connection string that is " + _
"valid for your system.")
End Try
End Sub
By Using ComboBox To Search
sql = " select * from english_language where lang=' " & ComboBox2.Text & " ' "
da = New OleDb.OleDbDataAdapter(sql, con)
Dim dt As New DataTable
da.Fill(dt)
DataGridView1.DataSource = dt
DataGridView1.Refresh()
Try this code to btnClear.
DataGridView.DataSource = 0
Press clear button. After that click the reload button that you coded.
I think it will reset and reload the data in data grid view.