Update SQL From DataGrid.

Windows Application:

When I have a user edit a field in my datagrid, how can I have it update SQL?  So if they edit lets say a BOOLEAN, and after the form is closed, the update to the grid, literally updates SQL?

I have never worked with anything other than generic SELECT and filling of the datagrid.  Never using the grid to modify the actual data in SQL.

Who is Participating?

Improve company productivity with a Business Account.Sign Up

sara110Connect With a Mentor Commented:
vb.net example

  Private Sub datagrid1_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dg1.DoubleClick
'dgindex is assume your primarykey string or integer : took primary key for updating that data
dgindex = datagrid1.Item(datagrid1.CurrentRowIndex, "0")
'you could access to each cell of your datagrid by changing "0" and using 1 ... instead
end sub

you could find some example in following websites , you need to hide your primary key in your datagrid and use it when you want to update and on double click event or other event or click ... you could update
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

chrisryhalAuthor Commented:
Sara110:  I am in VB, sorry, I don't know how to compare the code unfortuantly.  I am reviewing the examples you provided righ tnow.
the first example in vbhelper is very simple one
chrisryhalAuthor Commented:
Based on your first example, I have successfully populated the datagrid.  However, on closing of hte form as your example states, I get the following error if I lose focus on the row I am working with.:

          An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in system.data.dll
          Additional information: System error.

If I still have focus on the row I am changing, I dont get an error, but it doesn't update SQL.

\\\\\\\\\\\\\\\\\\\MY CODE MODIFIED FROM YOUR EXAMPLE\\\\\\\\\\\\\\\\

 Private Const SELECT_STRING As String = _
        "SELECT Top 50 * FROM TaskRost Order By [Database Number]"
    Private Const CONNECT_STRING As String = _
        "Data Source=;" & _
  "Initial Catalog=;" & _
  "User ID=;" & _

    ' The DataSet that holds the data.
    Private m_DataSet As DataSet

    ' Load the data.
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim data_adapter As SqlDataAdapter

        ' Create the SqlDataAdapter.
        data_adapter = New SqlDataAdapter(SELECT_STRING, CONNECT_STRING)

        ' Map Table to Contacts.
        data_adapter.TableMappings.Add("Table", "TaskRost")

        ' Fill the DataSet.
        m_DataSet = New DataSet

        ' Bind the DataGrid control to the Contacts DataTable.
        ' Changed by Jim Rogers (jrogers@antaresnet.com)
        dgContacts.SetDataBinding(m_DataSet, "TaskRost")
        'dgContacts.DataSource = m_DataSet.Tables("Contacts")
    End Sub

    ' Save any changes to the data.
    Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        If m_DataSet.HasChanges() Then
            Dim data_adapter As SqlDataAdapter
            Dim command_builder As SqlCommandBuilder

            ' Create the DataAdapter.
            data_adapter = New SqlDataAdapter(SELECT_STRING, CONNECT_STRING)

            ' Map Table to Contacts.
            data_adapter.TableMappings.Add("Table", "TaskRost")

            ' Make the CommandBuilder generate the
            ' insert, update, and delete commands.
            command_builder = New SqlCommandBuilder(data_adapter)

            ' Uncomment this code to see the INSERT,
            ' UPDATE, and DELETE commands.
            Debug.WriteLine("*** INSERT ***")
            Debug.WriteLine("*** UPDATE ***")
            Debug.WriteLine("*** DELETE ***")

            ' Save the changes.
        End If
    End Sub
you could inplace update data by writing code for changeEvent , or Click , end edit  or ... ,
my above code is for double click and  let your user to double click and have another select from your database using datatable to load information in textboxes and then easily update your data

for updating database when you have your primarykey and your updated data from your grid
by this method
dgindex = datagrid1.Item(datagrid1.CurrentRowIndex, "0")
then easily you could call your update function which could be like this

Public Function Updatefunction(strNewdata as string,PK as integer) As Boolean
      dim cnn As New SqlConnection
       cnn.ConnectionString = "server=ipaddressofyourServer;initial catalog=yourdatabaseName;User ID=sa;password="
        Dim cmdUpdate As New SqlCommand
            With cmdUpdate
                .Connection = cnn
                .Parameters.Add("@strNewdata", SqlDbType.VarChar, 200)
                .Parameters(0).Value = strnewdata

                        .CommandText = "update yourtablename set yourColumnName= @strNewData  WHERE ID  = '" & PK  & "'"
                End Select

            End With
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

chrisryhalAuthor Commented:
Quick question:

What is the correction of this line of code for SQL?

      Dim DBSchema As New OleDb.OleDbSchemaGuid

I am not seeing a SchemaGuid for SQL in the CLASS explorer.
I haven't used this class yet  but this is microsoft reference:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.