Adding and updating a record programmatically using .NETCF - vb.net

OK - I have worded this search 40 different ways and I seem to be lost here.
Every example I find seems so happy that you can easily drag and drop a datagrid and let the user fill it in -- then they stop!
I know how to do everything I am asking through LINQ. That obviously won't translate here. I really should have learned ADO.NET first, then LINQ, but NOoooo...
I need to know how to do the following in .NETCF (Windows Mobile 5) using a SQL CE database on the device.
Add a new record and populate some or all of the fields with data I supply. I don't need to add a record to a datagrid - sometimes the user will not even see the record. How do I add a new record -- put data into it and save it?
For example: Create a new delivery record, say, and have the program store the date in one field and a number in another field.
Search for a record, then update data in it.
Again, using LINQ I can do this easily -- I cannot for the life of me find any examples of doing it without it.
I can find lots of examples of populating a grid of databound fields, letting the user make changes then saving it out. I don't need to do that.
Say I need to search for the one record that meets a criteria (customerID=10 and orderID=1234), then when (if) that record is found, update a field in it.
Please let me know if you need any more info. I have done a lot of reading and just seem to be missing something!
Thanks in advance...

For #1, there are a few ways. Two easy, common ways are:
Use a SqlCeResultset, and create a row with it, then insert.
using(SqlCeConnection connection = new SqlCeConnection(myConnString))
using (SqlCeCommand cmd = new SqlCeCommand())
{
connection.Open();
cmd.CommandText = "MyTable";
cmd.CommandType = CommandType.TableDirect;
cmd.Connection = Connection;
SqlCeResultSet rs = cmd.ExecuteResultSet(ResultSetOptions.Updatable);
SqlCeUpdatableRecord record = rs.CreateRecord();
// do something to set your values in the record
rs.Insert(record);
}
Use a SqlCeCommand, set the command SQL and call ExecuteNonQuery.
using (SqlCeConnection connection = new SqlCeConnection(myConnString))
using (SqlCeCommand cmd = new SqlCeCommand())
{
connection.Open();
cmd.CommandText = "INSERT INTO MyTable(Foo) VALUES('bar')";
cmd.CommandType = CommandType.Text;
cmd.Connection = Connection;
cmd.ExecuteNonQuery();
}
For #2 it's not much different. Use an updateable resultset, seek to the record, modify and call Update or build your SQL and send it through the command using ExecuteScalar or ExecutNonQuery. The code is similar enough to those above that I'll leave it to you to work out.
A quick search on "SqlCeResultSet" and "example" or "update example" give loads of relevant results.

Also for anybody else searching this book also has a really good chapter on this procudere:
http://my.safaribooksonline.com/0321174046
I am still working my through this issue but making good progress,
Thanks for the help.

Thank you,
Between that and this code here, I think I am on my way.
Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click
Dim con As SqlCeConnection
con = New SqlCeConnection(("Data Source = " & Me.NorthwindDatabaseFullPath))
con.Open()
Dim sqlcdm As String = "INSERT INTO Orders VALUES(999, 'ALFKI', 1, 'RUDEDOG', '', '', '', '', '', 2, '11/15/1967', '11/16/1967', '11/17/1967', '23')"
Dim SqlCeCommand As New SqlCeCommand(sqlcdm, con)
SqlCeCommand.ExecuteNonQuery()
End Sub

Related

How can i set the value from the last row in an specific column in a variable in VB.Net

I'm develop an application using forms in vb.net with visual studio 2019
I have code in the event click for one button
Dim oda As New OleDbDataAdapter
Dim ods As New DataSet
Dim consulta As String
Dim cadena As New OleDbConnection
Dim comando As New OleDbCommand
Try
cadena.Open()
comando = New OleDbCommand("Insert into QRQC (Nombre,NumControl,Fecha,Hora,Turno)" &
"values(txt_nombre,txt_numControl,lbl_fecha,lbl_hora,cBox_turno)", cadena)
consulta = "Select *From QRQC"
oda = New OleDbDataAdapter(consulta, cadena)
ods.Tables.Add("QRQC")
oda.Fill(ods.Tables("QRQC"))
Dim row As Integer
row = ods.Tables("QRQC").Rows.Count - 1
courrentId = ods.Tables("QRQC")(row)("ID_QRQC").ToString()
frm_newPt2.lbl_folioQRQC.Text = courrentId
cadena.Close()
Catch ex As Exception
MsgBox("Error al generar el registro en la base de datos", vbCritical, "Aviso")
Console.WriteLine(ex)
cadena.Close()
GoTo skip
End Try
Everything goes perfectly, but when I delete some record on my DB this part of the code always return the value 102
courrentId = ods.Tables("QRQC")(row)("ID_QRQC").ToString()
How can i solve this problem?
First of all, your insert command is wrong, and will not work.
You have "values(txt_nombre. etc etc."
But that is just a string and NOT the actual values from the form. So you are actually going to "instert txt_nombre" into that table and NOT the value of that label or text box on the form!!!
So you need to fix and get your insert command working FIRST.
And if this is just editing data then consider using the data binder, since navigation, editing, deleting and saving of data to/from the table can occur 100% automatic whiteout ANY code on your part.
so first up is to fix that insert command. You can't JUST use a string with the names of the controls else that would actually as noted try to insert the names of the controls as text and NOT the values of the controls.
And lets clean up a few other things. No need for a dataset, since a dataset is a SET of tables - we only dealing with one table (so use a data table).
But as noted, before we mess with data tables, we have to fix that insert command.
It will, can look like this:
Dim strSQL As String
strSQL = "Insert into QRQC (Nombre,NumControl,Fecha,Hora,Turno) " &
"VALUES(#nombre,#numControl,#fecha,#hora,#turno)"
Using cmdSQL As New OleDbCommand(strSQL,
New OleDbConnection(My.Settings.TestDB))
cmdSQL.Parameters.Add("#nombre", OleDbType.Integer).Value = txt_nombre.Text
cmdSQL.Parameters.Add("#numControl", OleDbType.Integer).Value = txt_numControl.Text
cmdSQL.Parameters.Add("#fecha", OleDbType.Integer).Value = lbl_fecha.Text
cmdSQL.Parameters.Add("#hora", OleDbType.Integer).Value = lbl_hora.Text
cmdSQL.Parameters.Add("#turno", OleDbType.Integer).Value = txt_nombre.Text
cmdSQL.Connection.Open()
cmdSQL.ExecuteNonQuery()
End Using
So you have to "replace" the string values in the sql with the ACTUAL values you are using.
You also don't show where/how you setup your connection to the database. I guessed that you used the applications settings and the connection builder - so you have to change TestDB to your actual connection that you used.
The above will thus get your insert command working.
At that point, you can post a new question in that after you do a insert, how to get the new autonumber primary key, or whatever else you wanted to do, but your insert statement as written will not work.
As noted, perhaps it better to use data bound controls. This will result in a Access like design experience, and you not having to write ANY code to edit a table in vb.net.
And it not clear if the control names I used are correct (or they are even controls on the form), but if they are, then ".Text" is required to grab the values. You have to of course change (check) that the control names I used and guessed are correct.
You also have to change the data type "integer" I used in above to the correct data types. For text I recommend you use .VarWChar

Visual Basic Project fails to update Microsoft Access database

I have created a database that holds 3 values, the ID, UserName, and Score. I need to create a new entry to this database when the save button is clicked. My program needs to create a new row with the Username and score provided by the application.
This is my code to update an existing database:
Private Sub ButtonSaveScore_Click(sender As Object, e As EventArgs) Handles ButtonSaveScore.Click
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
dataFile = "F:\Documents\Class Documents\CSC289 - K6A - Programming Capstone Project\Project\Scoreboard.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
Using con As New OleDbConnection(connString),
cmd As New OleDbCommand("UPDATE [Scores] SET [UserName] = ?, [Score] = ? WHERE [ID] = ?", con)
con.Open()
cmd.Parameters.Add("#ID", OleDbType.Char).Value = "NEW"
cmd.Parameters.Add("#UserName", OleDbType.Char).Value = playerName
cmd.Parameters.Add("#Score", OleDbType.Char).Value = wins
cmd.ExecuteNonQuery()
End Using
End Sub
I get
oledb exception was unhandled
It highlights cmd.ExecuteNonQuery() and says data criteria mismatch.
Can someone give me advice to get this working?
You have a couple of issues there. Firstly, at least one of your parameters is the wrong data type. Secondly, your parameters are in the wrong order.
The Jet and ACE OLE DB providers only partially support named parameters, in that they allow you to use names so that your code can be clearer but they ignore the names and just use the positions. That means that you need to add the parameters to your OleDbCommand in the same order as they appear in the SQL code. You're not doing that so you have one issue there, although that's not the direct cause of your error message.
Even if those providers did fully support named parameters though, you're not using names in your SQL code. That means that there would be no way to match up parameters by name anyway, so how did you think that adding them in the wrong order wouldn't be an issue?
Given that all three of your parameters are specified as the same data type though, the incorrect order would not cause the error message you're seeing. If that data type was correct, you'd just find that the wrong data was saved to some of the columns, which would be even worse, i.e. appearing to work but not rather than just failing. You need to make sure that you use the correct OleDbType value for the column you're trying to save to. If your ID column in the database is specified to contain 32-bit numbers then you should be using OleDbType.Integer for the corresponding parameters. I'd also suggest using VarChar rather than Char unless your column is specifically fixed-width, which a Text column in Access is unlikely to be and I'm not sure even can be.

selecting from one database and inserting row to new database

I'm looking for a pseudo code to write a VB.NET cursor to select columns from one table in one database and inserting it into another table in a different database (they are *not on the same server) using data adapter etc.
I just need something to refer to as I learn. Thanks
Dim selectStr As String = _
"select * from db1"
Dim insertStr As String = _
"insert into db2(col1)"
Try
da_adapter = New OleDb.OleDbDataAdapter(selectStr, connStr)
da2_adapter = New OleDb.OleDbDataAdapter(insertStr, connStr2)
da_adapter.SelectCommand.CommandTimeout = 720
da_adapter.Fill(ds)
da2_adapter.SelectCommand.CommandTimeout = 720
da2_adapter.Fill(ds)
Catch ex As Exception
End Try
In your original code, this part is wrong:
da2_adapter = New OleDb.OleDbDataAdapter(insertStr, connStr2)
When you create a data adapter that way, the SQL statement you provide becomes part of the SelectCommand. You want yours to be part of the InsertCommand, which you need to do yourself:
Dim cmd2 As New OleDb.OleDbCommand(insertStr, connStr2)
da2_adapter = New OleDb.OleDbDataAdapter
da2_adapter.InsertCommand = cmd2
Also, you need to set the AcceptChangesDuringFill property of the first data adapter to False. That way, instead of setting the RowState of all the rows to Unchanged after populating the DataTable, they will remain as Added and ready to be inserted.
You then need to call Update on the second data adapter to save the data rather than calling Fill, which retrieves data.

excluding specific results from sql query and displaying the rest in a combo box - visual studio 2013

This has probably been asked somewhere before, but I have been searching for a while and cant find anything. I'm basically trying to create a sort-of internal messaging system in VB and am having trouble with a function that I'm working on. I already have a user database and secure login system and I'm now working on a form to send a message from user to user.
What I want to do is to run this query on form load:
SELECT usr_id, usrname FROM dbo.users
WHERE usrname NOT IN
(
SELECT ALL usrname
FROM dbo.users
WHERE usrname = '" & //textbox containing username that's logged in// & "'
)
I want to output the items to a Combobox. The purpose of this is so that (since it's an internal system for, say, employees to communicate) a user wouldn't necessarily have to know the username of the receiver in order to send them a message. I will be changing the function eventually to display the actual name of the user rather than the username, but I can add that in later and as of right now it's not important. Here is my code so far:
Private Sub NewMsg_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SqlConnection
con.ConnectionString = //connection string for database
Dim query As String = //query mentioned above
Try
con.Open()
Using sqlcmd As New SqlCommand(query, con)
Dim sqldr As SqlDataReader = sqlcmd.ExecuteReader
Dim dt As DataTable = New DataTable
dt.Load(sqldr)
sendtoBox.ValueMember = "usr_id"
sendtoBox.DisplayMember = "usrname"
sendtoBox.DataSource = dt
con.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Information)
con.Close()
End Try
End Sub
The query itself works perfectly when I run it on the SQL Server, and sure enough when the form loads users are displayed in the Combobox just like I want them to. The only problem is it's still including the username that I am trying to exclude. So I have reluctantly decided to ask for a little help because I can't figure out why it's not excluding the specified username :(
Any help will be appreciated. Thanks.
Problem was my own stupidity lol. Nothing wrong with the code itself, may be useful for someone so I will leave it up here :)
For the person who thinks this does not answer the question, I would like to initially state that I was the one who asked the question.
This was being used for a "Send Message" form, and the desired function was as follows:
GET CURRENTLY LOGGED IN USERS USERNAME FROM A TEXTBOX ON A DIFFERENT FORM! >
Connect to database >
Run a query against database to gather all users EXCEPT the logged in user >
Display results in a ComboBox.
The query was fine, the code was fine, everything was fine. The PROBLEM here was that when I was debugging the form I was NOT LOGGING IN and hence the TextBox that contained the username that I wanted to exclude was EMPTY, so instead of excluding say "admin" it was excluding "" because nobody was logged in.
So tell me, how is this not an answer? It was me being dumb that caused the problem in the first place, but the VB code and SQL query may help someone else, that is why I have left it up and answered by explaining that there is nothing wrong with the code. Get off your high-horse man...

Using TableAdapter to insert rows into a dataset does not do anything

I have a question similar to this one, but reading the (accepted) answer didn't give me much insight, so I'm hoping to state it more clearly and get a clearer response back.
I'm attempting to insert a data row into a table. I'm using TableAdapter's custom "insert nonQuery" that I wrote (it works, I tested) to accept some parameters. I'm fairly new to this business of communication with a database via .NET and what I'm doing is probably wrong by design. My questions are why is it wrong and what's the right way to do it? Both are equally important, IMO.
Here's some sample VB code I wrote:
Dim arraysTableAdapter As New UnitTestsDataSetTableAdapters.ArraysTableAdapter
Try
arraysTableAdapter.InsertArray("Test Array", 2, 1, 2, "Test user")
Catch ex As SqlException
MsgBox("Error occured when trying to add new array." _
& vbNewLine & vbNewLine _
& ex.Message)
End Try
...and that's pretty much it. There is no exception raised, my table does not get a new row inserted. Everything is just the way it was before I called the InsertArray method. When I test my query in the QueryBuilder with the same parameters, a new row gets added to the database.
Now, I do understand some of the reasons this would not work. I understand that I need to create and select a row in my DataSet (no idea how to do it) in order to tell the TableAdapter what it's adding the data to. Or at least I got that impression from reading the vast abyss of forums.
I would really like to use TableAdapter at some point, because it knows that .InsertArray exists and it knows which parameters it likes. I could try and do it using
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = connString
con.Open()
cmd.CommandText = "INSERT ...... all that jazz"
but it's not nearly clean enough for how clean I like my code to be. So, is there any way to do what I'm trying to do the way I'm doing it? In other words, how do I use the neat structure of a TableAdapter to communicate to my DataSet and put a new row in it?
Thanks in advance!
There were two things that were wrong:
(minor issue) I did not have a DataTable filled from the TableAdapter (see code below)
(major, sneaky issue) My method worked from the very beginning. There is nothing extra to be added except for the line above. However, the ConnectionString of arraysTableAdapter was pointing my program (automatically, by default) to a wrong location. Once I manually set the ConnectionString, it worked perfectly.
Here's my complete code:
Dim connString As String = "Some correct connection string"
Dim arraysDataTable As New SpeakerTestsDataSet.ArraysDataTable
Dim arraysTableAdapter As New UnitTestsDataSetTableAdapters.ArraysTableAdapter
'Set the correct connection string'
arraysTableAdapter.Connection.ConnectionString = conn
'Fill table from the adapter'
arraysTableAdapter.Fill(arraysDataTable)
Try
arraysTableAdapter.Insert("Test", 2, 1, 2, Now, Now, "Me")
Catch ex As Exception
MsgBox("Error occured when trying to add new array." _
& vbNewLine & vbNewLine _
& ex.Message)
End Try
The accepted answer in the question you linked to is correct, but sometimes saying it in different words helps:
A TableAdapter is used to communicate between a DataTable (there can be one or more DataTables in a DataSet) and a database. It can pull data from a database and add it to a DataTable and it can send data from a DataTable to the database. It's purpose is to create and execute the SQL code required to make this communication work.
You are trying to use the TableAdapter to directly add data to your DataTable. This will not work. Instead, you should use the methods that come with the DataTable to add a new row to the DataTable and then (if necessary) use your TableAdapter to send that row to a database.
For instance, with a Dataset called DataSet1 that contains a DataTable called DataTable1 that has three text columns you can add a record like this:
Dim d As New DataSet1
d.DataTable1.AddDataTable1Row("value1", "value2", "value3")
That AddDataTable1Row method is automatically created for you, and I think is what you are looking for.