The SelectCommand property has not been initialized before calling 'Fill' problem - vb.net

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

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

How to feed results of SQL statement into a GridView, not the SQL statement itself?

This has got to be close, but it's been a long day and I'm tired now so I can;t really see what the problem is. Basically, I have a table in SQL Server with 2 columns; one has the names of reports and the other has some SQL Scripts that I want to pass into a GridView, based on what a user selects from a ListBox. Here is my code.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim sqlConn As New SqlClient.SqlConnection("Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True")
sqlConn.Open()
Dim cmd As New SqlClient.SqlCommand("Select ReportName From [Table_1] order by ReportName", sqlConn)
Dim dsColumns As New DataSet
Dim daAdapter As New SqlClient.SqlDataAdapter(cmd)
daAdapter.Fill(dsColumns)
If dsColumns.Tables(0).Rows.Count > 0 Then
ListBox1.Items.Clear()
For i As Integer = 0 To dsColumns.Tables(0).Rows.Count - 1
ListBox1.Items.Add(dsColumns.Tables(0).Rows(i)(0).ToString())
Next
End If
Catch ex As Exception
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connetionString As String
Dim SqlStr As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim ds As New DataSet
Dim myItem As String
connetionString = "Data Source=EXCEL-PC\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True"
connection = New SqlConnection(connetionString)
'Dim iIndex As Integer = ListBox1.SelectedIndex
myItem = ListBox1.SelectedItem
SqlStr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
adapter = New SqlDataAdapter(SqlStr, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
I guess the problem is passing the SQL to the GridView. When I select the first Item, I see this in my GridView.
SELECT [OrderID]
,[CustomerID]
,[EmployeeID]
,[OrderDate]
,[RequiredDate]
,[ShippedDate]
,[ShipVia]
,[Freight]
,[ShipName]
,[ShipAddress]
,[ShipCity]
,[ShipRegion]
,[ShipPostalCode]
,[ShipCountry]
FROM [Test].[dbo].[Orders]
That's pretty close, but I want to get that SQL fed into the GridView, and get the results of the SQL displayed in the GridView, not eh SQL statement itself.
This is what I see now.
I want to see something more like this.
Finally, I am curious to know of the GridView can be made dynamic, so if I stretch out the window the GridView shows more columns. Now, if I stretch out the form window, the GridView stays static.
You need to actually run the retrieved Sql statement:
sqlstr = "select SqlScript from [Table_1] Where ReportName = '" & myItem & "'"
Try
connection.Open()
Dim cmd As New SqlCommand(sqlstr, connection)
Dim sqlstr_report As String = CStr(cmd.ExecuteScalar())
cmd.Dispose()
adapter = New SqlDataAdapter(sqlstr_report, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.DataSource = ds.Tables(0)
Use the .Anchor property of the DataGridView to make it resize with the form

Differences in populate a DataGridView using SQLiteDataAdapter vs. SQLiteDataReader

For populate a DataGridView with data from a SQLite DataBase I think the easy way is using SQLiteDataAdapter, populate a Table and make the Table the DataSource of the DataGridView, something like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles cdmDataTable.Click
Dim conn = New SQLiteConnection("Data Source=MyDataBase.sqlite;Version=3")
Try
Using (conn)
conn.Open()
Dim sql = "SELECT * FROM users"
Dim cmdDataGrid As SQLiteCommand = New SQLiteCommand(sql, conn)
Dim da As New SQLiteDataAdapter
da.SelectCommand = cmdDataGrid
Dim dt As New DataTable
da.Fill(dt)
DataGridView1.DataSource = dt
Dim readerDataGrid As SQLiteDataReader = cmdDataGrid.ExecuteReader()
End Using
Catch ex As Exception
MsgBox(ex.ToString())
End Try
Is there any advantage using SQLiteDataReader instead of SQLiteDataAdapter?
Data adapter is a higher level component that connects a DataTable to the underlying database. It can fill the DataTable and it can sync the changes on the DataTable back to the database. The DataAdapter uses a DataReader internally to read the data from the table.
There is no significant advantage using a DataReader over a DataAdapter to fill a DataTable.

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

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?