hello sir with this post i m sending my code enter code here
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Info.accdb")
Dim CommandStringX As String = "SELECT * FROM Table1"
Dim myadapter As New OleDbDataAdapter(CommandStringX, conn)
Dim cmdbuilderX = New OleDbCommandBuilder(myadapter)
myadapter.SelectCommand = New OleDbCommand(CommandStringX, conn)
myadapter.InsertCommand = cmdbuilderX.GetInsertCommand
myadapter.UpdateCommand = cmdbuilderX.GetUpdateCommand 'not needed now
myadapter.DeleteCommand = cmdbuilderX.GetDeleteCommand 'not needed now
myadapter.Fill(dtset)
Try
conn.Open()
myadapter.FillSchema(dtset, SchemaType.Mapped) 'make your dataset tables like the ones in your Access database
dtset.Tables("Table1").Rows(0)("Phone Number") = txtPhoneNumber.Text
dtset.Tables("Table1").Rows(0)("Message") = txtMsg.Text
myadapter.Update(dtset) 'Update Access database based on dtset
Catch ex As OleDbException
MsgBox(ex.ToString)
Finally
conn.Close()
End Try
MY problem is that i hav created database and it is empty with specific colums defined by me but there is no data after defining that columns ... i want to store data at runtime so when i execute that it shows me an error like this " null refernce exception was unhandled " at this line
dtset.Tables("Table1").Rows(0)("Phone Number") = txtPhoneNumber.Text
Please help regarding this
You need to execute a sql insert statement to push data into your tables.
If there's no data in the table, then there's no row to access. Thus, the object which is not set in that line is Rows(0). You can't reference the first row in the collection if there are no rows to reference.
It looks like what you're trying to do is add a row to Table1 in your DataSet. Here's some information on how to do that. Essentially, the steps are:
Create a new DataRow using the schema present in the DataTable.
Populate that row with data.
Add that row to the Rows collection in the DataTable.
Related
i was trying to insert record from one table to another using Data Set, first here's the code:
Try
Dim ds1 As New DataSet
Dim dbada2 As New OleDbDataAdapter
Dim dbbl2 As New OleDbCommandBuilder
Dim dbcon As OleDbConnection = New OleDbConnection(dbconstring)
dbcon.Open()
Dim cmd1 As OleDbCommand = New OleDbCommand("SELECT InspectionID, ICTDIR, UnitDescription, SizeType, QuantityNo, SerialNo FROM DeliveryInspection WHERE ICTDIR = #ictdir", dbcon)
cmd1.Parameters.AddWithValue("#ictdir", txtRefNo.Text)
Dim dbada1 As New OleDbDataAdapter(cmd1)
ds1.Clear()
dbada1.Fill(ds1)
dbcon.Close()
dbcon.Open()
dbada2 = New OleDbDataAdapter("SELECT * FROM LogSUF", dbcon)
dbada2.Update(ds1)
dbcon.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString, "DBADA 2 Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
here i have 2 DataAdapters, The first one is from the table DeliveryInspection and the second is from LogSUF. both tables have the same Column with the only difference is that LogSUF has no records.
I want to make a system that will insert a record from DeliveryInspection (with the corresponding ICTDIR from the Text Box where the user typed it which is txtRefNo) to the LogSUF. My code doesn't have error but it doesn't work either and i tried some ways to fix this problem. Please help and also is there another way to do this? I'm a beginner.
When you call Update, only the rows with a RowState of Added, Modified or Deleted will be saved. As it stands, all your rows have a RowState of Unchanged, so there's nothing to save.
The solution is to set AcceptChangesDuringFill to False on the first data adapter, before you call Fill. That way, the AcceptChanges method is not called implicitly when you call Fill and each RowState will remain Added, ready for the row to be inserted when you call Update.
I have some problems here. I need help.
Recently, I have created a local database called stock.mdf and the application will be getting all the data from the hosting MySQL database into this local SQL Server database.
I am using sqlBulkCopy to inserting all the data. I have tried to view it after inserting. But when I close my application, I head back to check the table data. It does not inserted. Why is that?
Here is my code:
Here will be retrieving the data from the hosting
Dim connStr As String = "server=xxxx;user=xxx;database=xxx;password=xxxx;"
Dim conn As New MySqlConnection(connStr)
Dim cmd As New MySqlCommand
Dim Adapter As New MySqlDataAdapter
Dim StockData As New DataTable
Try
Dim SQL As String = "SELECT * FROM stock"
Console.WriteLine("Connecting to MYSQL.....")
conn.Open()
cmd.Connection = conn
cmd.CommandText = SQL
Adapter.SelectCommand = cmd
Adapter.Fill(StockData)
' StockViewGrid.DataSource = StockData
Catch ex As Exception
Console.WriteLine(ex.ToString())
Finally
conn.Close()
Console.Write("Done")
End Try
This will be the places where sqlBulkCopy working:
As well, I am trying to view from the stock table.
Dim Local_connectionStr As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|stock.mdf;Integrated Security=True"
Dim Local_conn As New SqlConnection(Local_connectionStr)
Dim Local_cmd As New SqlCommand
Dim Local_Adapter As New SqlDataAdapter
Dim Local_StockData As New DataTable
Try
Using sqlBulkCopy As New SqlBulkCopy(Local_conn)
'Set the database table name
sqlBulkCopy.DestinationTableName = "stock"
'[OPTIONAL]: Map the DataTable columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("stockId", "stockId")
sqlBulkCopy.ColumnMappings.Add("id_android", "id_android")
sqlBulkCopy.ColumnMappings.Add("itemCode", "itemCode")
sqlBulkCopy.ColumnMappings.Add("quantity", "quantity")
Local_conn.Open()
sqlBulkCopy.WriteToServer(StockData)
Local_conn.Close()
End Using
Catch ex As Exception
Console.WriteLine(ex.ToString())
Finally
Local_conn.Close()
Console.Write("Done")
End Try
Try
Dim SQL As String = "SELECT * FROM stock"
Console.WriteLine("Connecting to MYSQL.....")
Local_conn.Open()
Local_cmd.Connection = Local_conn
Local_cmd.CommandText = SQL
Local_Adapter.SelectCommand = Local_cmd
Local_Adapter.Fill(Local_StockData)
StockViewGrid.DataSource = Local_StockData
Catch ex As Exception
Console.WriteLine(ex.ToString())
Finally
Local_conn.Close()
Console.Write("Done")
End Try
Since I can't comment (not enough points) I will put my thoughts here. Can you check that you got the expected data with a
Console.WriteLine(StockData.Rows.Count.ToString)
Console.ReadLine()
Also, your destination table doesn't have a PK that is auto increment, does it?
Sorry about the comment as an answer. (Untested code)
Unfortunately your code extracts are lacking headers etc, so are not complete, and I cannot be absolutely certain, BUT in your retrieving routine you seem to be declaring StockData as a local variable. This means that, although this may well be being filled with the data from MySQL, it is immediately discarded on exiting from this routine. Therefore the StockData variable in the sqlBulkCopy routine will be empty, and therefore will insert nothing. You need to fix your scope and make sure that the StockData read from MySQL is the same StockData used in SqlBulkCopy.
how can i populate multiple table into multiple DataGridview?
for example i have 3 tables which is table1, table2 and table3, and in my form i have 3 dataGridView with name of dataGridView1, dataGridView2 and dataGridView3. i found this solution Updating an Access Database via a DataGridView Using OLEDB in VB.NET as a result of my code.
function loadDatabaseDataToGridView
Dim msAccessFilePath As String
Dim con As New OleDbConnection
Dim dataTable, dataTable2, dataTable3, dataTable4 As New DataTable
Dim olebDataAdapter As New OleDbDataAdapter
Dim da As New OleDbDataAdapter
Dim dataSet As New DataSet
Private Sub loadDatabaseDataToGridView()
Try
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & msAccessFilePath
dataSet.Tables.Add(dataTable)
olebDataAdapter = New OleDbDataAdapter("Select * from table1", con)
olebDataAdapter.Fill(dataTable)
olebDataAdapter = New OleDbDataAdapter("Select * from table2", con)
olebDataAdapter.Fill(dataTable2)
olebDataAdapter = New OleDbDataAdapter("Select * from table3", con)
olebDataAdapter.Fill(dataTable3)
DataGridView1.DataSource = dataTable.DefaultView
DataGridView2.DataSource = dataTable2.DefaultView
DataGridView3.DataSource = dataTable3.DefaultView
Dim cb = New OleDbCommandBuilder(olebDataAdapter)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
MessageBox.Show("Successfull")
Catch ex As Exception
MessageBox.Show("Failed")
con.Close()
End Try
con.Close()
End Sub
function SaveChanges
'Perform this on Button Save is Click
Private Sub saveChanges()
olebDataAdapter.Update(dataSet)
End Sub
This code is working as excpected, it is populating the data from MS Access file but when i clicked the button save to save the changes on edited data, an error has occurred.
THE ERROR:
Concurrency violation: the UpdateCommand affected 0 of the expected 1 records
anyone does know how to properly implement of what i am trying to achieve? Thank You Very Much!!!
Each DataAdapter object only has a single UpdateCommand, so you'll need one for each data table. If it runs the update command and no rows are updated (because the update command is actually for a table that you haven't changed) then you'll get the Concurrency Violatation.
It actually gets more complicated than this if your tables are related as the order that inserts, updates and deletions occur can be critical.
If you create a Strongly Typed Dataset it generates designer code that includes a TableAdapterManager class and all of the required data adapters. It might be worth playing around with this just so that you can see how the generated code works.
Just a note, the 'Concurrency violation' exception is actually there so that you can design an update command that will only succeed if the contents of the record in the database match the data held locally (to prevent you from overwriting another user's changes). Search for Optimistic Locking for more details.
I have the following code to alter the data, now I actually want to write said data back to the TESTS_TMP table in the Access database, how do I do that? I thought the adapter update did that but it doesn't?
Dim dataSet As DataSet = New DataSet
Using connection As New OleDbConnection(FileLocations.connectionStringNewDb)
connection.Open()
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand("SELECT * FROM TESTS_TMP;", connection)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(adapter)
adapter.Fill(dataSet)
'MsgBox(dataSet.Tables(0).Rows.Count)
'Code to modify the data in the DataSet here.
Dim id As Integer = 300
For i As Integer = 0 To dataSet.Tables(0).Rows.Count - 1
dataSet.Tables(0).Rows(i).Item(0) = id
id = id + 1
Next
' Without the OleDbCommandBuilder this line would fail.
'builder.GetUpdateCommand()
'adapter.Update(dataSet)
Try
adapter.Update(dataSet.Tables(0))
dataSet.AcceptChanges()
Catch x As Exception
' Error during Update, add code to locate error, reconcile
' and try to update again.
End Try
End Using
MsgBox(dataSet.Tables(0).Rows(1).Item(0))
You're calling AcceptChanges. and it is marking all of the rows as being unmodified, so they are never updated in the database. Remove this call.
I have two Combo-Boxes like this
I need to create an auto-fill feature for the 1st Combo-Box. It should list the EmployeeID if Search-By Field is specified as Employee-Number. Similarly it should list Employee First Name along with Last Name if the Search-By Field is Employee-Name.
How can I do this? I have no clue, I am doing this for the first time. I am using SQLite, Visual Studio 2010.
Dim mySelectQuery As String = "SELECT " & Search & " FROM EmployeeTable WHERE Status LIKE '" & Status & "'"
Dim myConnString As String = "Data Source=" & Application.StartupPath & "\Database\SimpleDB.db3"
Dim sqConnection As New SQLiteConnection(myConnString)
Dim sqCommand As New SQLiteCommand(mySelectQuery, sqConnection)
sqConnection.Open()
Try
' Always call Read before accessing data.
Dim sqReader As SQLiteDataReader = sqCommand.ExecuteReader()
Dim j As Integer = sqReader.FieldCount
While sqReader.Read()
'''''''''''''''''''''''Here, Don't know how to list the items from the query reult into the combo-box
End While
'Close Reader after use
sqReader.Close()
Catch ex As Exception
'Show Message on Error
MsgBox(ex.ToString)
Finally
'At Last Close the Connection
sqConnection.Close()
End Try
I'm not sure entirely what you are asking but I think this is it.
In the SelectedIndex changed event you would have something similar to the code below. You can add an If statement to check what you are querying for and adjust your query accordingly.
Dim dt as New DataTable
Try
Using sqlConn
sqlConn.Open()
Using cmd As New SqlCommand("your query")
cmd.Connection = sqlConn
cmd.CommandType = CommandType.Text
Dim reader as SqlDataReader = cmd.ExecuteReader()
dt.Load(reader)
End Using
End Using
Catch ex As SqlException
Throw New Exception(ex.Message)
End Try
With yourComboBox
.DataSource = dt
.DataValueField = "columName you want to be the value of the item"
.DataTextField = "columnName of the text you want displayed"
End With
Notice the following properties for the combo-box: AutoCompleteMode, AutoCompleteSource, AutoCompleteCustomSource.
Select the appropriate AutoCompleteMode. See details on the different modes at this link.
For AutoCompleteSource, choose either ListItems (in which case the source will be the items of the ComboBox) or CustomSource. Should you choose CustomSource, set the appropriate source as the value of the ComboBox's AutoCompleteCustomSource property.
This should provide you with enough details to do what you're looking for.
The other requirements you've listed - such as taking the data from an SQLite database or changing between employee name and employee number - won't affect the way you work with the AutoComplete feature.