Update unable to find TableMapping['z'] or DataTable 'z' - sql

Private Sub dgviewshow()
Dim da As New SqlDataAdapter
da = New SqlDataAdapter("select * from Student", con)
Dim dset As New DataSet
da.Fill(dset, "z")
dgview.DataSource = dset.Tables("z")
dgview.AutoSizeColumnsMode = DataGridViewAutoSizeColumnMode.Fill
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles btnUpdate_1.Click
Dim da As New SqlDataAdapter
da = New SqlDataAdapter("select * from Student", con)
Dim a As New SqlCommandBuilder(da)
Try
a.GetUpdateCommand()
da.Update(dset, "z")
MsgBox("Successfully updated", MsgBoxStyle.Information)
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub

In your dgviewshow method, you populate a DataTable in a DataSet that is assigned to a local variable dset. In your Button1_Click_1 method, you are trying to save changes from a DataSet assigned to a different dset variable. Presumably it is also a different DataSet. If you want to access the DataSet in multiple methods then it must be assigned to a variable that is accessible in multiple methods, i.e. a member variable. If you're using a member variable, which you must be already or that second method wouldn't compile, then why are you declaring a local variable in the first method at all?

Related

where should i put the button save codes into this codes that i sent here? because i'd like to save into another table

i put this code because i used combobox and they fill my two textbox,but when try to save its not saving the data that i put
this is the code
Sub loaddata()
Try
reload("SELECT * FROM NAME", STUDENT)
STUDENT.DataSource = dt
STUDENT.DisplayMember = "NAME"
STUDENT.ValueMember = "ID"
Catch ex As Exception
End Try
End Sub
Private Sub NAME_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NAME.SelectedIndexChanged
Try
Dim sql As String
Dim cmd As New OleDbCommand
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
strcon.Open()
sql = "SELECT * FROM STUDENT where NAME LIKE '%" & NAME.Text & "%'"
cmd.Connection = strcon
cmd.CommandText = sql
da.SelectCommand = cmd
da.Fill(dt)
If dt.Rows.Count > 0 Then
GENDER.Text = dt.Rows(0).Item("GENDER").ToString
ADDRESS.Text = dt.Rows(0).Item(" ADDRESS").ToString
End If
Catch ex As Exception
Finally
strcon.Close()
End Try
End Sub
please show me how to put the save codes here,because i use only the BindingNavigator1 to save, but it does not save, sorry if my grammar is wrong because i'm not a fluent in english
I know we have a language barrier but we are both trying our best. I have provided a few examples of code to interact with a database.
It is a good idea to keep you database code separate from you user interface code. If you want to show a message box in you Try code, keep the Try in the user interface code. The error will bubble up from the database code to the calling code.
Using...End Using blocks take care of disposing of database objects. Parameters protect against Sql injection because parameter values are not considered executable code by the database. Note that for OleDb data sources the order that the parameters appear in the sql statement must match the order that they are added to the Parameters collection.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim dt = GetOriginalData()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
ComboBox1.DataSource = dt
End Sub
Private Function GetOriginalData() As DataTable
Dim dt As New DataTable
Using cn As New OleDbConnection("Your first connection string"),
cmd As New OleDbCommand("Select ID, Name From Table1;")
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
InsertData(CInt(ComboBox1.SelectedValue), ComboBox1.SelectedText, txtGender.Text, txtAddress.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub InsertData(id As Integer, name As String, gender As String, address As String)
Using cn As New OleDbConnection("Your second connection string"),
cmd As New OleDbCommand("Insert Into Table2 (ID, Name, Gender, Address) Values (#ID, #Name, #Gender, #Address);", cn)
With cmd.Parameters
.Add("#ID", OleDbType.Integer).Value = id
.Add("#Name", OleDbType.VarChar).Value = name
.Add("#Gender", OleDbType.VarChar).Value = gender
.Add("#Address", OleDbType.VarChar).Value = address
End With
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

Fatal error encountered during command execution.'

I want to save the rows of datagridview into the database. I am using editbtn click button, when I press the button it gives me the following error: "Fatal error encountered during command execution." Here is the code which I am using
Private Sub Supplier_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn.ConnectionString = "Server=127.0.0.1;Database=pembelian;Uid=root;Pwd=;"
If conn.State = ConnectionState.Open Then
conn.Close()
End If
conn.Open()
disp_data()
End Sub
Public Sub disp_data()
cmd = conn.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = "select * from supplier"
cmd.ExecuteNonQuery()
Dim dt As New DataTable()
Dim da As New MySqlDataAdapter(cmd)
da.Fill(dt)
DataGridView1.DataSource = dt
End Sub
Private Sub edit_btn_Click(sender As Object, e As EventArgs) Handles edit_btn.Click
Dim query As String = "updates supplier set nama=#nama, alamat=#alamat where npwp=#npwp"
cmd = New MySqlCommand(query, conn)
cmd.Parameters.AddWithValue("#nama", nama.Text)
cmd.Parameters.AddWithValue("#alamat", alamat.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Data berhasil di update")
disp_data()
End Sub
First of all, it's not good to re-use the same connection object throughout your application. There is a feature in ADO.Net called connection pooling, where the MySqlConnection object you use in your code is actually a simple wrapper for the real underlying connection. These real connections are much heavier and more expensive to manage. They handle the real work of authentication, getting network socket resources, negotiating with the server, etc.
When you try to re-use the same connection object, you are optimizing the small thing (MySqlConnection) at the expense of the big thing (the real underlying connections). Don't do that.
Instead, you really are much better off creating a new connection for most queries, and then returning it to the pool as quickly as possible. This is normally handled with a Using block.
That out of the way I can look at the actual question. I noticed the #npwp parameter is not defined in the last method. Guessing at the name of the appropriate field, you want something more like this:
Private Sub edit_btn_Click(sender As Object, e As EventArgs) Handles edit_btn.Click
Dim query As String = "updates supplier set nama=#nama, alamat=#alamat where npwp=#npwp"
Using conn As New MySqlConnection("Server=127.0.0.1;Database=pembelian;Uid=root;Pwd=;")
Using cmd As New MySqlCommand(query, conn)
cmd.Parameters.AddWithValue("#nama", nama.Text)
cmd.Parameters.AddWithValue("#alamat", alamat.Text)
cmd.Parameters.AddWithValue("#npwp", npwp.Text)
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Data berhasil di update")
disp_data()
End Sub
Public Sub disp_data()
Dim dt As New DataTable()
Dim query As String = "select * from supplier"
Using conn As New MySqlConnection("Server=127.0.0.1;Database=pembelian;Uid=root;Pwd=;")
Using cmd As New MySqlCommand(query, conn)
Using da As New MySqlDataAdapater(cmd)
da.Fill(dt)
End Using
End Using
End Using
DataGridView1.DataSource = dt
End Sub

textbox AutoComplete not working after a search query

Hello there I am quite new to windows form programming, and my project requires me to do a search query on my database. I would like the option for the names that can be currently searched to be displayed when typing, however, after pressing the search button the autocomplete no longer displays when I try to look for another attribute. https://i.stack.imgur.com/Wytdy.png , https://i.stack.imgur.com/Qjy5q.png
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(mSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customers")
dt = ds.Tables(0)
MaxRows = ds.Tables("customers").Rows.Count
con.Close()
Dim msSQL As String = "SELECT * FROM customers;"
dgvCustomerInfo.DataSource = display(msSQL, "customers")
Try
dt = New DataTable
con.Open()
With cmd
.Connection = con
.CommandText = "SELECT DISTINCT fname FROM customers"
End With
da.SelectCommand = cmd
da.Fill(dt)
Dim r As DataRow
txtSearchName.AutoCompleteCustomSource.Clear()
For Each r In dt.Rows
txtSearchName.AutoCompleteCustomSource.Add(r.Item(0).ToString)
Next
''''''''''''''''''''''''
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
da.Dispose()
I believe your problems stem from the AutoCompleteMode. Suggest and SuggestAppend seem to fill in the text box as expected. Append seem to do nothing. I don't think this is working as intended.
I tested with a little database I have. It is Sql Server but should work the same for Sqlite. I used a bit of Linq magic to get the AutoCompleteCustomSource. A few other changes... Using...End Using blocks ensure that database objects are closed and disposed. You don't need a DataAdapter, just a DataTable and Command.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetDataForTextBox()
Dim strArray = dt.AsEnumerable().[Select](Function(x) x.Field(Of String)("Name")).ToArray()
TextBox5.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim MySource As New AutoCompleteStringCollection()
MySource.AddRange(strArray)
TextBox5.AutoCompleteCustomSource = MySource
TextBox5.AutoCompleteMode = AutoCompleteMode.SuggestAppend
End Sub
Private Function GetDataForTextBox() As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select Distinct Name From Coffees", cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = GetSearchResults(TextBox5.Text)
DataGridView1.DataSource = dt
End Sub
Private Function GetSearchResults(name As String) As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select * From Coffees Where Name = #Name", cn)
cmd.Parameters.Add("#Name", SqlDbType.VarChar, 100).Value = name
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function

The SelectCommand property has not been initialized before calling 'Fill' problem

The SelectCommand property has not been initialized before calling 'Fill' problem:
Private Sub DeleteButton_Click(sender As Object, e As EventArgs) Handles DeleteButton.Click
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Dim row As New Integer
Try
ds = New DataSet
tables = (ds.Tables)
da = New OleDbDataAdapter
da.Fill(ds, "Booking")
Dim cmdstr As String = "delete * from [Booking] where ID = " & DataGridView1.SelectedRows(0).Cells(0).Value.ToString()
Dim cmd As New OleDbCommand(cmdstr, objCon)
da.SelectCommand = cmd
objCon.Open()
cmd.ExecuteNonQuery()
objCon.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Change
da.SelectCommand = cmd
With
da.DeleteCommand = cmd
Reguarding the Dim statements at the beginning of your code; you never use tables, source1 or row in your code so, there is no point in declaring them.
On to the Try You assign a New DataSet to ds. This is empty so assigned the Tables collection to tables makes no sense. This will be empty also.
Next you create a New DataAdapter. A new DataAdapter has no select command so it will be unable to .Fill anything.
Then you assign a Delete command to the SelectCommand property of a DataAdapter. This makes no sense.
Finally you execute you command. This should work if wasn't for the other code.
Keep you Database objects local so you can control their closing and disposing. Using...End Using takes care of this for you. The Using also acts as a Dim statement so it also declares you variables. You can include more than one variable with a single Using by separating them by a comma.
I guessed at the datatype of you ID field. Check your database.
Private Sub DeleteButton_Click(sender As Object, e As EventArgs) Handles DeleteButton.Click
Try
Using cn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand("delete * from [Booking] where ID = #ID", cn)
cmd.Parameters.Add("#ID", OleDbType.Integer).Value = DataGridView1.SelectedRows(0).Cells(0).Value
cn.Open()
cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

Checking a PIN number is correct according to it's card number

I'm currently working on an assignment for college that I'm really stuck on. I have to create an application to simulate an ATM machine using Visual Basic 2010. I'm currently stuck trying to check whether the PIN number entered in the text box is correct for the card number selected in the combo box. If the user enters the PIN incorrectly three times, the card is confiscated. I am getting an error message at the moment saying "Object variable or With block variable not set". Below is the code I have written:
Imports System.Data.OleDb
Public Class PinEntry
Public connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Users\ben\Documents\Programming\Year 2\Visual Studio\Assignment2\BankOfGlamorgan\EDP2011-BoG.mdb"
Friend connectionBG As New OleDbConnection
Dim ds As New DataSet
Dim da As New OleDbDataAdapter
Dim commandCardNumber As New OleDbCommand()
Dim dr As OleDbDataReader
Dim pinErrorCount As Integer
Dim ATMCardsBindingSource As New BindingSource
Dim SqlCommandCheckPIN As New OleDbCommand
Dim SqlCommandConfiscate As New OleDbCommand
Private Sub PinEntry_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connectionBG.ConnectionString = connectionString
commandCardNumber.Connection = connectionBG
commandCardNumber.CommandType = CommandType.Text
commandCardNumber.CommandText = "SELECT cardNumber FROM ATMCards"
Try
connectionBG.Open()
da.SelectCommand = commandCardNumber
da.Fill(ds, "ATMCards")
cmbCardNumber.DataSource = ds.Tables("ATMCards")
cmbCardNumber.DisplayMember = "cardNumber"
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connectionBG.Close()
End Try
End Sub
Private Sub btnEnterPin_Click(sender As Object, e As EventArgs) Handles btnEnterPin.Click
Try
Me.connectionBG.Open()
Dim PIN As String
Dim cardNo As String
PIN = Me.txtPIN.Text
cardNo = Me.ATMCardsBindingSource.Current("cardNumber")
Me.SqlCommandCheckPIN.Parameters("#PIN").Value = PIN
Me.SqlCommandCheckPIN.Parameters("#cardNumber").Value = cardNo
Dim dr As OleDbDataReader = Me.SqlCommandCheckPIN.ExecuteReader()
If dr.HasRows And pinErrorCount <= 2 Then
My.Forms.Menu.ShowDialog()
dr.Close()
pinErrorCount = 0
txtPIN.Text = ""
ElseIf pinErrorCount = 2 Then
dr.Close()
MessageBox.Show("PIN Entered Incorrectly Three Times Card Now Confiscated", "Card Taken", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
cardNo = Me.ATMCardsBindingSource.Current("cardNumber")
Me.SqlCommandConfiscate.Parameters("#cardNumber").Value = cardNo
Me.SqlCommandConfiscate.ExecuteNonQuery()
Else
pinErrorCount = pinErrorCount + 1
MessageBox.Show("Incorrect PIN Please Try Again.", "Incorrect PIN", MessageBoxButtons.OK, MessageBoxIcon.Error)
txtPIN.Text = ""
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
Me.connectionBG.Close()
End Try
End Sub
End Class
Updated code below:
Imports System.Data.OleDb
Public Class PinEntry
Public connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Users\ben\Documents\Programming\Year 2\Visual Studio\Assignment2\BankOfGlamorgan\EDP2011-BoG.mdb"
Friend connectionBG As New OleDbConnection
Dim ds As New DataSet
Dim da As New OleDbDataAdapter
Dim commandCardNumber, commandPinNumber As New OleDbCommand()
Dim dr As OleDbDataReader
Dim pinErrorCount, cardNumber, PIN As Integer
Dim oForm As Menu
Dim userInput As String
Private Sub PinEntry_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connectionBG.ConnectionString = connectionString
commandCardNumber.Connection = connectionBG
commandCardNumber.CommandType = CommandType.Text
commandCardNumber.CommandText = "SELECT cardNumber FROM ATMCards"
commandPinNumber.Connection = connectionBG
commandPinNumber.CommandType = CommandType.Text
commandPinNumber.CommandText = "SELECT PIN FROM ATMCards WHERE cardNumber = ?"
Try
connectionBG.Open()
da.SelectCommand = commandCardNumber
da.Fill(ds, "ATMCards")
cmbCardNumber.DataSource = ds.Tables("ATMCards")
cmbCardNumber.DisplayMember = "cardNumber"
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connectionBG.Close()
End Try
End Sub
Private Sub btnEnterPin_Click(sender As Object, e As EventArgs) Handles btnEnterPin.Click
cardNumber = Convert.ToInt16(cmbCardNumber.Text)
commandPinNumber.Parameters.Add(New OleDbParameter())
commandPinNumber.Parameters(0).Value = cardNumber
Try
connectionBG.Open()
dr = commandPinNumber.ExecuteReader()
While dr.Read()
PIN = dr.Item("PIN").ToString
End While
dr.Close()
If PIN = userInput Then
MsgBox("Correct PIN")
Else
MsgBox("Incorrect PIN")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
connectionBG.Close()
End Try
End Sub
Private Sub txtPIN_TextChanged(sender As Object, e As EventArgs) Handles txtPIN.TextChanged
userInput = txtPIN.Text
End Sub
End Class
OleDBCOmmand objects are typically used in a more disposable way than as module level variables. In order to work, they also need a SQL string and a Connection object associated with them. Ex:
Dim sql As String = "SELECT etc etc etc WHERE something = ?"
Using cmd As New OleDbCommand(Sql, dbCon)
cmd.Parameters.AddWithValue("#p1", myVar)
cmd.Parameters.AddWithValue("#p2", myVar)
Dim rdr As OleDbDataReader = cmd.ExecuteReader
If rdr.HasRows Then
' do something interesting
End If
End Using
Here, both the SQL and DB Connection are associated with the Command Object when it is created. The Using block assures it is properly disposed of when we are done with it.
Also, OleDbCommand objects do not support named parameters. Usually, it just ignores them. The right way for Paramters is shown (ie AddWithValue) where you replace each ? placeholder in the SQL string in order with the actual value. Do be sure the data type matches. If PIN is a number, you must add a number, not Text.
For the SQL, you are testing the PIN entered against a card number, so those are the param values. Depending on how you construct the SQL you can either see if the PIN in the DB matches the one they gave OR just see if you get any rows back.