0

My database program is fully functional and when I add new entries to the database they appear on my DataGridView correctly. However after I close the program these changes are not saved. How do I save the changes back to the database? Here's my code:

    Dim conn As New SqlClient.SqlConnection(My.Settings.MainDatabaseConnectionString)
    Dim query As String = "INSERT INTO Users VALUES('Something','Test');"
    Dim cmd As New SqlClient.SqlCommand(query, conn)
    Dim reader As SqlClient.SqlDataReader

    'Open Connection
    conn.Open()
    'Execute Query
    reader = cmd.ExecuteReader
    'Close Connection
    conn.Close()

    'Update DataGridView
    Me.UsersTableAdapter.Fill(Me.UsersDataSet.Users)

2 Answers 2

3

As you've discovered, you need more the a reader :)

There are many ways to go. This link gives a reasonable example:

http://msdn.microsoft.com/en-us/library/ms972948.aspx

The key thing:

To start, the GridView's SqlDataSource must contain an UpdateCommand with appropriate parameters.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to insert something into the DB you can do this

Dim mySQLCommand As Data.SqlClient.SqlCommand
mySQLCommand.CommandText = "INSERT INTO Users VALUES('Something','Test');"
mySQLCommand.ExecuteNonQuery()

you might also want to parameterize your variables to prevent sql injections

mySQLCommand.Parameters.Add("@variable_name", SqlDBType.NvarChar).value = variable

and using @variable_name in the insert

mySQLCommand.CommandText = INSERT INTO Users VALUES(@variable_name, @variable_name2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.