Refresh a datagrid in another form - vb.net

I am using VB to make something to change records in a database. I have a table called tblCustomers. When the user clicks a button on the homeForm, a new form called FormNewCustomer appears which has text boxes for the user to input info to put in the database. After submitting it, the data does get inserted, but it doesn't show in the datagridview.
This is my code:
Imports System.Data.OleDb
Public Class FormNewCustomer
Public connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=ProgramDatabase.accdb"
Public conn As New OleDbConnection(connstring)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
Me.Close()
End Sub
Private Sub btnCopy_Click(sender As Object, e As EventArgs) Handles btnCopy.Click
If txtCustomerName.Text = "" Or txtAC.Text = "" Then
MsgBox("Enter a Customer Name and a Customer Reference.")
Else
conn.Open()
Dim SqlQuery As String = "INSERT INTO tblCustomers (CustomerName,AC,Address,Phone,Email) VALUES (#CustomerName,#AC,#Address,#Phone,#Email)"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Parameters.AddWithValue("#CustomerName", txtCustomerName.Text)
.Parameters.AddWithValue("#AC", txtAC.Text)
.Parameters.AddWithValue("#Address", txtAddress.Text)
.Parameters.AddWithValue("#Phone", txtPhone.Text)
.Parameters.AddWithValue("#Email", txtEmail.Text)
.Connection = conn
.ExecuteNonQuery()
End With
conn.Close()
MsgBox("Successfully added new Customer.")
FormHome.DataGridView1.Refresh()
Me.Close()
End If
End Sub
End Class

Try this Code:
Dim objDataGridView As YourFormClassName = New YourFormClassName
objDataGridView.ShowDialog()

Related

How can I make a datagridview live connected to an access database stored locally in VB.NET?

I would like it so when I delete/edit a record from the datagridview, it will automatically delete/edit the access database file. Here is a snippet of my code which loads the database into the datagridview.
Public Function dbConnect() As Boolean
Try
cn = New OleDbConnection(DataBasePath)
cn.Open()
'MessageBox.Show("is work ")
Return True
Catch ex As Exception
MessageBox.Show("Unable to open the database: " & ex.Message)
Return False
End Try
End Function
Private Function GetOrders() As DataTable
Dim dtOrders As New DataTable
dbConnect()
Dim SQLCMD As New OleDbCommand
SQLCMD.Connection = cn
SQLCMD.CommandText = "Select * From [OrdersTbl]"
dtOrders.Load(SQLCMD.ExecuteReader())
Return dtOrders
End Function
Private Sub EditOrdersForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
OrdersDataGrid.DataSource = GetOrders()
End Sub
How can I make it so that changes are saved to the local file.
I have a datagridview and a button on the form. Here's the code you can refer to:
Private dt As DataTable = New DataTable
Private da As OleDbDataAdapter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connection As OleDbConnection = New OleDbConnection("your connection string")
connection.Open()
Dim cmdTxt As String = "SELECT * FROM yourTable"
da = New OleDbDataAdapter(New OleDbCommand(cmdTxt, connection))
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(da)
da.Fill(dt)
Dim source As BindingSource = New BindingSource With {
.DataSource = dt
}
DataGridView1.DataSource = source
connection.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
DataGridView1.EndEdit()
da.Update(dt)
End Sub
Every time you want to update database from your datagridview, just click the button.

System.InvalidOperationException ExecuteNonQuery requires an open and available Connection

The following code is supposed to display information from a database but there is an error (the title of this question) on the DBCmd.ExecuteNonQuery() line of code.
Does anyone know how I can resolve this problem?
• I am using VB.NET
• I am using an Access database
The code is:
Imports System.Data.OleDb
Public Class frmCheckAvailablity
Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=|DataDirectory|\NewHotel.mdb;")
Private Access As New DBControl
Dim QRY As String
Private DBCmd As OleDbCommand
Dim DBDR As OleDbDataReader
Public DBDA As New OleDbDataAdapter("SELECT RoomType FROM tblRoomBookings", DBCon)
Public DT As New DataTable
Public DS As New DataSet
Public DR As DataRow
Private Function NotEmpty(text As String) As Boolean
Return Not String.IsNullOrEmpty(text)
End Function
Private Sub frmCheckAvailability_Shown(sender As Object, e As EventArgs) Handles Me.Shown
'RUN QUERY
Access.ExecQuery("SELECT * FROM tblRoomBookings ORDER BY BookingID ASC")
If NotEmpty(Access.Exception) Then MsgBox(Access.Exception) : Exit Sub
End Sub
Private Sub frmCheckAvailability_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'NewHotelDataSet.tblRoomBookings' table. You can move, or remove it, as needed.
Me.TblRoomBookingsTableAdapter.Fill(Me.NewHotelDataSet.tblRoomBookings)
If DBCon.State = ConnectionState.Closed Then DBCon.Open() : Exit Sub
End Sub
Private Sub Search()
DBDA.Fill(DT)
txtSearch.AutoCompleteCustomSource.Clear()
For Each DBDR In DT.Rows
txtSearch.AutoCompleteCustomSource.Add(DBDR.Item(0).ToString)
Next
txtSearch.AutoCompleteMode = AutoCompleteMode.SuggestAppend
txtSearch.AutoCompleteSource = AutoCompleteSource.CustomSource
End Sub
Private Sub SearchCustomers(RoomType As String)
'ADD PARAMETERS & RUN QUERY
Access.AddParam("#RoomType", "%" & RoomType & "%")
Access.ExecQuery("SELECT * FROM tblRoomBookings WHERE RoomType LIKE #RoomType")
'REPORT & ABORT ON ERRORS
If NotEmpty(Access.Exception) Then MsgBox(Access.Exception) : Exit Sub
End Sub
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
QRY = "SELECT FullName FROM tblRoomBookings WHERE RoomType'" & txtSearch.Text & "'"
DBCmd = New OleDbCommand(QRY, DBCon)
DBCmd.ExecuteNonQuery()
DBDR = DBCmd.ExecuteReader
If DBDR.Read Then
txtRoomType.Text = DBDR("RoomType")
txtFirstNight.Text = DBDR("FirstNight")
txtLastNight.Text = DBDR("LastNight")
txtNoNights.Text = DBDR("NoNights")
End If
End Sub
The only place in the code that I see DBcmd.ExecuteNonQuery is in search text changed event. Do really want to run this code every time the users types a letter?
Do not create a new connection at the class (Form) level. Every time the connection is used it needs to be disposed so it can be returned to the connection pool. Using...End Using blocks handle this for you even if there is an error.
Don't call .ExecuteNonQuery. This is not a non query; it begins with Select.
You can't execute a command without an Open connection.
Never concatenate strings for sql statments. Always use parameters.
The connection is open while the reader is active. Don't update the user interface while the connection is open.
Load a DataTable and return that to the user interface code where you update the user interface.
Private ConStr As String = "Your connection string"
Private Function GetSearchResults(Search As String) As DataTable
Dim dt As New DataTable
Dim QRY = "SELECT FullName FROM tblRoomBookings WHERE RoomType = #Search"
Using DBcon As New OleDbConnection(ConStr),
DBCmd As New OleDbCommand(QRY, DBcon)
DBCmd.Parameters.Add("#Search", OleDbType.VarChar).Value = Search
DBcon.Open()
Using reader = DBCmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
Dim dtSearch = GetSearchResults(txtSearch.Text)
If dtSearch.Rows.Count > 0 Then
txtRoomType.Text = dtSearch(0)("RoomType").ToString
txtFirstNight.Text = dtSearch(0)("FirstNight").ToString
txtLastNight.Text = dtSearch(0)("LastNight").ToString
txtNoNights.Text = dtSearch(0)("NoNights").ToString
End If
End Sub

Delete selected row from DataGridView and MS-Access Database

I am trying to delete the selected row from DataGridView and MS-Access database..
Private Sub ButtonEditDelete_Click(sender As Object, e As EventArgs) Handles ButtonEditDelete.Click
If Not Connection.State = ConnectionState.Open Then
Connection.Close()
End If
Try
If Me.DataGridViewEdit.Rows.Count > 0 Then
If Me.DataGridViewEdit.SelectedRows.Count > 0 Then
Dim intStdID As Integer = Me.DataGridViewEdit.SelectedRows(0).Cells("Username").Value
Connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Johnster\documents\visual studio 2015\Projects\Cash register\Cash register\Database11.accdb;Jet OLEDB:Database Password="
Connection.Open()
Command.Connection = Connection
Command.CommandText = "DELETE From MasterUser WHERE ID=? And Username=? And UserFullname=? AND Password=?"
Dim res As DialogResult
res = MsgBox("Are you sure you want to DELETE the selected Row?", MessageBoxButtons.YesNo)
If res = DialogResult.Yes Then
Command.ExecuteNonQuery()
Else : Exit Sub
End If
Connection.Close()
End If
End If
Catch ex As Exception
End Try
End Sub
Replace your (Try) Part with this code:
Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Johnster\documents\visual studio 2015\Projects\Cash register\Cash register\Database11.accdb;Jet OLEDB:Database Password=")
cn.Open()
Try
For Each row As DataGridViewRow In DataGridViewEdit.SelectedRows
Using cm As New OleDbCommand
cm.Connection = cn
cm.CommandText = "DELETE * FROM CheckDJ WHERE [Username]= #myuser"
cm.CommandType = CommandType.Text
cm.Parameters.AddWithValue("#myuser", CType(row.DataBoundItem, DataRowView).Row("Username"))
cm.ExecuteNonQuery()
End Using
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
cn.Close()
End Using
then clear your datasource of datagridview by this line:
DataGridViewEdit.Datasource = nothing
then repeat the code part that is responsible of filling the datagridview from the database
You are going about this in very much the wrong way. The proper way to do it would be to use an OleDbDataAdapter to populate a DataTable, bind that to a BindingSource and bind that to your DataDridView. You can then call RemoveCurrent on the BindingSource to set the RowState of the DataRow bound to the selected DataGridViewRow to Deleted. You then use the same OleDbDataAdapter to save the changes from the DataTable back to the database. The Fill method of the data adapter retrieves data and the Update method saves changes. You can call Update every time there's a change to save or you can let the user make all there changes locally first and then save them all in a single batch. Here's a code example:
Private connection As New OleDbConnection("connection string here")
Private adapter As New OleDbDataAdapter("SELECT ID, Name, Quantity, Unit FROM StockItem",
connection)
Private builder As New OleDbCommandBuilder(adapter)
Private table As New DataTable
Private Sub InitialiseDataAdapter()
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
End Sub
Private Sub GetData()
'Retrieve the data.
adapter.Fill(table)
'Bind the data to the UI.
BindingSource1.DataSource = table
DataGridView1.DataSource = BindingSource1
End Sub
Private Sub SaveData()
'Save the changes.
adapter.Update(table)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitialiseDataAdapter()
GetData()
End Sub
Private Sub deleteButton_Click(sender As Object, e As EventArgs) Handles deleteButton.Click
BindingSource1.RemoveCurrent()
End Sub
Private Sub saveButton_Click(sender As Object, e As EventArgs) Handles saveButton.Click
SaveData()
End Sub
In certain circumstances, you may not be able to use an OleDbCommandBuilder and would have to create the InsertCommand, UpdateCommand and DeleteCommand yourself.

Update statement in sql doesnt work , microsoft access with vb.net

I currently doing the changepassword function in my vb.net project, user can click change password to change their password
But my code doesnt update correctly , it will show "updated" but when i go to my database access table the data still remain the same
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.IO
Public Class frmUserDetail
Dim ds As New DataSet
Dim dt As New DataTable
Dim cmd As SqlCommand
Dim con As SqlConnection
Dim da As New OleDbDataAdapter
Dim conn As New OleDbConnection
Private Sub FrmUserDetail_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\phoneOnline.accdb;Persist Security Info=false;")
loadUserDetail()
txtUserName.Enabled = False ' set it to false so user cannot do shit with it
End Sub
Public Sub loadUserDetail()
conn.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\phoneOnline.accdb;Persist Security Info=false;")
Dim cmd As OleDbCommand
Dim userName As String = frmMain.lblUserLogin.Text
'specify name of the user
Dim search As String = "SELECT * from tblUser WHERE UserName= '" + userName + "'"
cmd = New OleDbCommand(search)
cmd.Connection = conn
Dim dtt As New DataTable()
Dim daa As New OleDbDataAdapter(cmd)
daa.Fill(dtt)
If dtt.Rows.Count() > 0 Then
txtUserName.Text = dtt.Rows(0)(0).ToString 'show the userName
txtUserPassword.Text = dtt.Rows(0)(1).ToString 'show the password of the user
txtEmail.Text = (dtt.Rows(0)(2).ToString) 'show user email
Else
MsgBox("You are currently login as a guest")
End If
End Sub
Private Sub changePassword()
If cbChangePassword.Checked Then
txtChangePassword.Enabled = True
Else
txtChangePassword.Enabled = Not (True)
End If
End Sub
Private Sub CbChangePassword_CheckedChanged(sender As Object, e As EventArgs) Handles cbChangePassword.CheckedChanged
changePassword()
End Sub
Private Sub BtnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
conn.Open()
Dim cmd As OleDbCommand
Dim sql As String = "UPDATE tblUser SET UserPassword=#userpass,Email=#email WHERE UserName=#userName;"
cmd = New OleDbCommand(sql.ToString, conn)
cmd.Parameters.AddWithValue("#username", txtUserName.Text)
cmd.Parameters.AddWithValue("#userpass", txtChangePassword.Text)
cmd.Parameters.AddWithValue("#email", txtEmail.Text) 'pass the time variable from the form 1 to the parameter
cmd.ExecuteNonQuery()
MsgBox("updated")
conn.Close()
End Sub
Private Sub BtnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Hide()
frmMain.Show()
End Sub
End Class
I Expect my database will get updated when i updated it

how to insert checked items from checkedlistbox to SQL database?

I am trying to save checked items from a checkedlistbox to my SQL database and i am filling my checkedlistbox from the same SQL database,So far i am able to get the text of checked item from the checkedlistbox and i saved it in a string then i used a label to display if i am getting the text of checked item or not and its working but when i try to insert the checked data in database i get a error "Connection property has not been initialized." on ExecuteNonQuery() method.
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim da As New SqlDataAdapter
Dim dt As New DataTable
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.ConnectionString = connectionString
conn.Open()
Dim str As String
str = "Select sem1 From sem"
da = New SqlDataAdapter(str, conn)
dt = New DataTable
da.Fill(dt)
CheckedListBox1.DataSource = dt
CheckedListBox1.DisplayMember = "sem1"
conn.Close()
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String
Dim cmd As New SqlCommand
Dim sql As String
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim itemChecked As Object
For Each itemChecked In CheckedListBox1.CheckedItems
str = itemChecked.item("sem1").ToString
Label1.Text = str
sql = "insert into pretab(pre) values('" + str + "')"
cmd.ExecuteNonQuery()
Next
conn.Close()
End Using
End Sub
End Class
This error
The problem maybe arised from your query syntax. Try this:
sql = "insert into pretab(pre) values(#str)"
cmd.Parameters.AddWithValue("#str", str)
cmd.ExecuteNonQuery()
OOPS.. I just realised that you forgot to assign your command with connection. So, please try to add the following statement:
cmd = New SqlCommand(sql, conn)
befor execution your command. So the final code should look like this:
sql = "insert into pretab(pre) values(#str)"
cmd = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#str", str)
cmd.ExecuteNonQuery()
First off I would do data operations in a class e.g. (note I focus on inserts). You need to change server and catalog to your server and catalog on SQL-Server.
Imports System.Data.SqlClient
Public Class Operations
Private Server As String = "KARENS-PC"
Private Catalog As String = "CheckedListBoxDatabase"
Private ConnectionString As String = ""
Public Sub New()
ConnectionString = $"Data Source={Server};Initial Catalog={Catalog};Integrated Security=True"
End Sub
Public Function Read() As DataTable
' read rows for checked listbox here
End Function
Public Sub Insert(ByVal sender As List(Of String))
Using cn As SqlConnection = New SqlConnection With {.ConnectionString = ConnectionString}
Using cmd As SqlCommand = New SqlCommand With {.Connection = cn, .CommandText = "insert into pretab(pre) values (#pre)"}
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#pre", .SqlDbType = SqlDbType.NVarChar})
cn.Open()
For Each item In sender
cmd.Parameters("#pre").Value = item
cmd.ExecuteNonQuery()
Next
End Using
End Using
End Sub
End Class
Form code
Public Class Form1
Private ops As New Operations
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Result = CheckedListBox1.Items.OfType(Of String).Where(Function(item, index) CheckedListBox1.GetItemChecked(index)).ToList
ops.Insert(Result)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckedListBox1.DataSource = ops.Read
CheckedListBox1.DisplayMember = "sem1"
End Sub
End Class
It appears that you did not provide the connection to the command. Your code was button click
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str As String
Dim cmd As New SqlCommand
Dim sql As String
Dim connectionString As String = "Server=DESKTOP-V12PTAV ;Database=test ;User Id=sa ;Password=wills8877"
Using conn As New SqlConnection(connectionString)
conn.Open()
Dim itemChecked As Object
For Each itemChecked In CheckedListBox1.CheckedItems
str = itemChecked.item("sem1").ToString
Label1.Text = str
sql = "insert into pretab(pre) values('" + str + "')"
cmd.ExecuteNonQuery()
Next
conn.Close()
End Using
End Sub
What you need to do is before cmd.ExecuteNonQuery() you need to provide it a connection cmd.connection = connectionString
this will remove the cmd.ExecuteNonQuery() error.