How to get count of records in a table? - vb.net

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

Related

Index out of range exception cannot find column

Hello I have this problem in came upon when trying to do simple manual search in vb.net. It says System.IndexOutOfRangeException: 'Cannot find column 4.'
could anyone explain what this means i am quite new to coding and dont quite get what i could to do fix this. In the attached database i have only one table called customer with 4 columns custid, custfname, custlname and dob.
This is the code and the error occurs in the btnNext and Navigaterecords. The database was made in sqlite
Imports System.Data.SQLite
Public Class Form1
Dim inc As Integer
Dim MaxRows As Integer
Dim ConnectionString As String = "Data Source=dbRoomBookings.db"
Dim ds As New DataSet
Dim dt As New DataTable
Dim mSQL As String = "SELECT * FROM Customer"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(mSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customer")
dt = ds.Tables(0)
MaxRows = ds.Tables("customer").Rows.Count
con.Close()
Dim msSQL As String = "SELECT * FROM customer;"
dgvSearchResults.DataSource = display(msSQL, "customer")
End Sub
Private Sub BtnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If inc <> MaxRows - 1 Then
inc = inc + 1
txtCusId.Text = ds.Tables("customer").Rows(inc).Item(0)
txtFname.Text = ds.Tables("customer").Rows(inc).Item(1)
txtLname.Text = ds.Tables("customer").Rows(inc).Item(2)
cboDay.Text = ds.Tables("customer").Rows(inc).Item(3)
cboMonth.Text = ds.Tables("customer").Rows(inc).Item(4)
cboYear.Text = ds.Tables("Customer").Rows(inc).Item(5)
Else
MsgBox("no more rows")
End If
End Sub
Sub navigaterecords()
txtCusId.Text = ds.Tables("customer").Rows(inc).Item(0)
txtFname.Text = ds.Tables("customer").Rows(inc).Item(1)
txtLname.Text = ds.Tables("customer").Rows(inc).Item(2)
cboDay.Text = ds.Tables("customer").Rows(inc).Item(3)
cboMonth.Text = ds.Tables("customer").Rows(inc).Item(4)
cboYear.Text = ds.Tables("customer").Rows(inc).Item(5)
txtDbo.Text = ds.Tables("customer").Rows(inc).Item(3) & "/" & ds.Tables("customer").Rows(inc).Item(4) & "/" & ds.Tables("customer").Rows(inc).Item(5)
End Sub
Private Sub BtnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
If inc > 0 Then
inc = inc - 1
navigaterecords()
Else
MsgBox("no more rows")
End If
End Sub
Private Sub BtnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
If inc <> 0 Then
inc = 0
navigaterecords()
End If
End Sub
Private Sub BtnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
If inc <> MaxRows - 1 Then
inc = MaxRows - 1
navigaterecords()
Else
End If
End Sub
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim sSQL As String
Dim newds As New DataSet
Dim newdt As New DataTable
If txtSearchFname.Text <> "" Then
sSQL = "SELECT * FROM customer WHERE custfname LIKE'" & txtSearchFname.Text & "%'"
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(sSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(newds, "customer")
newdt = newds.Tables(0)
dgvSearchResults.DataSource = newdt
con.Close()
ElseIf txtSearchId.Text <> "" Then
sSQL = "SELECT * FROM customer WHERE custid ='" & txtSearchId.Text & "'"
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(sSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(newds, "customer")
newdt = newds.Tables(0)
dgvSearchResults.DataSource = newdt
con.Close()
End If
End Sub
Private Sub BtnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim con2 As New SQLiteConnection
Dim da2 As New SQLiteDataAdapter
Dim dsql, qsql As String
Dim ds2 As New DataSet
Dim dt2 As DataTable
con2 = New SQLiteConnection(ConnectionString)
dsql = "DELETE FROM customer WHERE custid = " & txtSearchId.Text & ""
qsql = "SELECT * FROM customer"
Dim cmd As New SQLiteCommand(qsql, con2)
con2.Open()
da2.DeleteCommand = con2.CreateCommand
da2.DeleteCommand.CommandText = dsql
da2.DeleteCommand.ExecuteNonQuery()
MsgBox("Row(s) Deleted !! ")
Dim da3 As New SQLiteDataAdapter(cmd)
da3.Fill(ds2, "customer")
dt2 = ds2.Tables(0)
dgvSearchResults.DataSource = dt2
con2.Close()
End Sub
Private Sub BtnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim con3 As New SQLiteConnection
Dim da3 As New SQLiteDataAdapter
con3 = New SQLiteConnection(ConnectionString)
Dim usql As String = "UPDATE Customer SET custfname = '" & txtFname.Text & "'" & "WHERE custid =" & CInt(txtCusId.Text) & ""
con3.Open()
da3.UpdateCommand = con3.CreateCommand
da3.UpdateCommand.CommandText = usql
da3.UpdateCommand.ExecuteNonQuery()
MsgBox("Row Updated")
End Sub
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim isql As String = "INSERT INTO customer(custfname, custlname, dob) VALUES('" _
& txtFname.Text & "','" & txtLname.Text & "','" & cboYear.Text _
& "-" & cboMonth.Text & "-" & cboDay.Text & "');"
Dim msql As String = "SELECT * FROM customer"
add(isql)
'refresh the Data Grid
dgvSearchResults.DataSource = display(msql, "customer")
End Sub
End Class
Here is the specific documentation on IndexOutOfRangeException: https://learn.microsoft.com/en-us/dotnet/api/system.indexoutofrangeexception
For visibility, the definition is:
The exception that is thrown when an attempt is made to access an
element of an array or collection with an index that is outside its
bounds.
In your case, you are trying to get a value by passing the index of a column but the index you're passing is greater than the total number of columns.
Assuming that your table definition has the following columns: custfname, custlname, and dob, the following represents when the Exception would occur:
Get column 0, returns the value of custfname
Get column 1, returns the value of custlname
Get column 2, returns the value of dob
Get column 3, throws an IndexOutOfRangeException
The same thing would also happen if you tried to get a value at a negative index too.
You have a 4-column table which will have indexes from 0 to 3 only:
custid is column 0, custfname is column 1, custfname is column 2, and dob is column 3.
So any attempt to access ds.Tables("customer").Rows(inc).Item(4) (and (5), etc) will yield an Index out of range exception.
But you seem to know that the table only has 4 columns; why are you then attempting to access columns that you know don't exist? I'm a bit confused by that. If you're trying to split DOB into day/month/year, you'll have to manipulate the dob value from the DOB composite column, Item(3).

Why I get this error in Vb.net while connecting mysql “Conversion from string to type ‘Double’ is not valid”?

I tried the equation separately. It worked. But after I joined, i got the error of conversion. My aim is to get MySql data to the vb.net So I can check some values and develop the project. I have to finish the project within one week and I don’t know how to finish this. If this seems easy please forgive me.
Imports MySql.Data.MySqlClient
Public Class Form3
Dim conn As MySqlConnection
Dim command As MySqlCommand
Dim cmd As MySqlCommand
Dim Da As New MySqlDataAdapter
Dim ds As New DataSet
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'To check whether the date is same
TextBox1.Text = System.DateTime.Now.ToString(("MM/dd/yyyy"))
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
conn = New MySqlConnection
conn.ConnectionString = "server=localhost;user=root;password=1234;database=attendance"
Dim reader As MySqlDataReader
Try
ds.Clear()
conn.Open()
'Checking Subject Now
cmd = New MySqlCommand("select Subject_Name from dateverification", conn)
Da = New MySqlDataAdapter(cmd)
Da.Fill(ds, "dateverification")
TextBox2.Text = ds.Tables(0).Rows(0).Item(0)
'Checking Todays Date
cmd = New MySqlCommand("select Today_Date from dateverification", conn)
Da = New MySqlDataAdapter(cmd)
Da.Fill(ds, "dateverification")
Label1.Text = ds.Tables(0).Rows(0).Item(0)
'Checking Count1
cmd = New MySqlCommand("select Count1 from dateverification", conn)
Da = New MySqlDataAdapter(cmd)
Da.Fill(ds, "dateverification")
Label2.Text = ds.Tables(0).Rows(0).Item(0)
'Checking Count2
cmd = New MySqlCommand("select Count2 from dateverification", conn)
Da = New MySqlDataAdapter(cmd)
Da.Fill(ds, "dateverification")
Label3.Text = ds.Tables(0).Rows(0).Item(0)
'If the days are Different, Total days will be counted and Date will be updated
If Label1.Text <> TextBox1.Text Then
Label1.Text = System.DateTime.Now.ToString(("yyyy-MM-dd"))
Label2.Text = Label2.Text + 1
Dim query1 As String
query1 = "UPDATE attendance.dateverification SET Today_Date = '" & Label1.Text & "' , Count1 = '" & Label2.Text & "' WHERE Subject_Name = '" & TextBox3.Text & "'; "
command = New MySqlCommand(query1, conn)
reader = command.ExecuteReader
MessageBox.Show("Welcome to New Day")
Else
'If the date are equal, then the number of counts which register wasopen in same day will be increased
Label3.Text = Label3.Text + 1
Dim query1 As String
query1 = "UPDATE attendance.dateverification SET Count2 = '" & Label3.Text & "' WHERE Subject_Name = '" & TextBox3.Text & "'; "
command = New MySqlCommand(query1, conn)
reader = command.ExecuteReader
MessageBox.Show("You are still on the same day")
End If
Dim query As String
query = "UPDATE attendance.dateverification SET Subject_selected = '" & TextBox3.Text & "' WHERE Subject_Name = '" & TextBox3.Text & "'; "
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
Probably, the error is because this code is not always legal:
Label3.Text = Label3.Text + 1
Label3.Text is a string. Depending on compiler options, you can't just expect the compiler to convert it to a number for you. Those options are there to help you, and you should use them.
Moving on.
Not 100% sure on MySql, but in Sql Server for sure you could do all this as one connection command job in the database. This will perform better, and helped me greatly simplify the code.
Pay special attention to how I used parameters. It's NEVER okay to use string concatenation to put parameter values into a query. This is too important even for learning or proof of concept code.
Option Strict On
Option Infer On
Imports System
Imports MySql.Data.MySqlClient
Public Class Form3
'Don't try to keep the connection/command objects at the form level!
'Do keep the connection string here:
Private ConnectionString As String = "server=localhost;user=root;password=1234;database=attendance"
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = Today.ToString("MM/dd/yyyy")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim conn As SqlConnection
'I put two statements in one command string,
' and the CASE expressions let me get all of the updates into one statement
Dim sql As String =
"UPDATE attendance.dateverification
SET Count1 = CASE WHEN Today_Date <> current_date THEN Count1 + 1 ELSE Count1 END,
Count2 = CASE WHEN Today_Date = current_date THEN Count2 + 1 ELSE Count2 END,
Today_Date = current_date,
Subject_selected = #subject
WHERE Subject_Name = #subject;
SELECT Subject_Name, Today_Date, Count1, Count2
FROM dateverification"
' Also note: this string could be a constant if we wanted to!
Try
conn = New MySqlConnection(ConnectionString)
Dim cmd As New MySqlCommand(sql, conn)
'Use actual type and length here
cmd.Parameters.Add("#subject", MySqlDbType.VarString, 50).Value = TextBox3.Text
conn.Open()
Dim rdr As MySqlDataReader = cmd.ExecuteReader()
rdr.Read()
TextBox2.Text = rdr("Subject_Name").ToString()
Label1.Text = rdr("Today_Date").ToString()
Label2.Text = rdr("Count1").ToString()
Label3.Text = rdr("Count2").ToString()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
End Class

Read data from a database in vb.net

So I used this piece of sample code to retrieve data from a MS Access Database and display it on a few textboxes on the form. The following error occurs -
# dr = cmd.ExecuteReader - Data type mismatch in criteria expression.
dr = cmd.ExecuteReader
This is the sample code -
Dim provider As String
Dim dataFile As String
Dim connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\example\Desktop\Data.accdb" ' Change it to your Access Database location
connString = provider & dataFile
myConnection.ConnectionString = connString
End Sub
Dim r As Random = New Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
myConnection.Open()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
Dim str As String
str = "SELECT * FROM Items WHERE (Code = '" & r.Next(1, 3) & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
TextBox1.Text = dr("Description").ToString
TextBox2.Text = dr("Cost").ToString
TextBox3.Text = dr("Price").ToString
End While
myConnection.Close()
End Sub
Try this ..
str = "SELECT * FROM Items WHERE (Code = '" & (r.Next(1, 3)).ToString() & "')"
try this:
str = "SELECT * FROM Items WHERE (Code = '" & cStr(r.Next(1, 3)) & "')"
The table name in the file that you provided for download is "Table1" not "Items".
Change the query string to:
str = "SELECT * FROM Table1 where (Code = '" & r.Next(1, 3) & "')"

Syntax error in UPDATE statement access database in vb.net

I have just started learning VB.net for several weeks. i want to make a form and send data from a text box to a specific cell in ms access database (*.accdb) file. but the code i have writen gives the following error:
Syntax error in UPDATE statement.
i have checked several books and spent hours on internet, but no answer!
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim cnn1 As New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=
E:\Ebook\hararat\GUI\Heat Exchanger Designer\heat.accdb"
con.Open()
sql = "SELECT * FROM flow1"
da = New OleDbDataAdapter(sql, con)
da.Fill(ds, "flow1")
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("flow1").Rows(1).Item(1) = "name"
da.Update(ds, "flow1")
con.Close()
You need to use the .QuotePrefix and .QuoteSuffix properties of the OleDbCommandBuilder to wrap table and field names in square brackets. That is, instead of just
Dim cb As New OleDb.OleDbCommandBuilder(da)
you need to do
Dim cb As New OleDb.OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
That will generate an UPDATE statement of the form
UPDATE [TableName] SET [ColumnName]= ...
which is necessary if the table name or any of the field names happen to be reserved words in Access SQL.
Try this one
dim sqlupdate as string = "UPDATE tablename SET column_name = '" & textname.text & "' WHERE column_name = '" & textname.text & "'"
Sometimes errors occur when using the following column names: Username, Password, Date, Time, and much more of this type, try to avoid these column names because this might cause the problem of your issue regarding updating tables. Enable for you to update this kind of column name you need to enclose it with [ and ] so it comes like this: [Username], [Date], etc. so the syntax might go like this:
UPDATE tablename SET [Username] = '" & textname.text & "' WHERE column_name = '" & textname.text & "'"
my codes goes like this:
Open_Con()
Dim sqlUpdate As String
Dim sqlUpdatePass As DialogResult
sqlUpdate = "UPDATE tblAccounts SET [Password] = '" & txtRPassword.Text & "' WHERE [Username] = '" & txtUsername.Text & "'"
sqlCmd = New OleDbCommand(sqlUpdate, sqlCon)
Try
sqlUpdatePass = MessageBox.Show("Are you sure to save this changes?", "Save changes?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If sqlUpdatePass = vbYes Then
sqlCmd.ExecuteNonQuery()
MsgBox("Changes are now saved", MsgBoxStyle.Information, "New password has been set.")
Call ClearAll()
Me.Hide()
Else
Exit Sub
End If
Catch ex As Exception
MsgBox("Could not perform this task because " & ex.Message, MsgBoxStyle.Exclamation, "Error")
End Try
sqlCmd = Nothing
sqlCon.Close()
hope this things mention above codes helps your problem. have a nice day and happy coding :)
dim sqlupdate as string="UPDATE [tablename] SET [column_name] = '"& textname.text &"' WHERE [column_name] = '"& textname.text &"';"
By enclose attributes with square brackets, it appears to work I have tried it, it works
Imports System.Data.OleDb
Imports System.Data
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database2DataSet.identitas' table. You can move, or remove it, as needed.
Me.IdentitasTableAdapter.Fill(Me.Database2DataSet.identitas)
End Sub
Public Sub clean()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
End Sub
Public Sub read()
Call openconn()
str = "select * from identitas"
dtadapter = New OleDbDataAdapter(str, con)
Dim dg As New DataTable
dg.Clear()
dtadapter.Fill(dg)
dgv.DataSource = dg
End Sub
Public Sub create()
Call openconn()
str = "insert into identitas values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "') "
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
MsgBox("data lebet")
read()
clean()
End Sub
Public Sub update()
Call openconn()
str = "UPDATE identitas SET [Nama] = '" & TextBox2.Text & "',[Alamat] = '" & TextBox3.Text & "', [No] = '" & TextBox4.Text & "' where [NIK] = '" & TextBox1.Text & "'"
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
MsgBox("data ter ubah")
clean()
read()
End Sub
Public Sub delete()
Call openconn()
str = "delete from identitas where NIK = '" & TextBox1.Text & "'"
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
clean()
End Sub
Private Sub btnclose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclose.Click
Me.Close()
End Sub
Private Sub btnc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnc.Click
create()
End Sub
Private Sub btnr_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnr.Click
read()
End Sub
Private Sub btnclean_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclean.Click
clean()
End Sub
Private Sub btnd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnd.Click
Dim pesan As String = MsgBox("yakin mau hapus = " & TextBox1.Text & "?", MsgBoxStyle.YesNo)
If pesan = vbYes Then
delete()
End If
read()
End Sub
Private Sub btnu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnu.Click
update()
End Sub
End Class
I had same problem, this helped.
"Sometimes errors occur when using the following column names: Username, Password, Date, Time, and much more of this type, try to avoid these column names because this might cause the problem of your issue regarding updating tables. Enable for you to update this kind of column name you need to enclose it with [ and ] so it comes like this: [Username], [Date], etc. so the syntax might go like this: "
I renamed the columns in Access (e.g Password1,Username1) as the same words password, username might be reserved in vb.net. Thanks for this response.

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.