Solved

Update SQL From DataGrid.

Posted on 2006-11-21
12
385 Views
Last Modified: 2012-05-05
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.

0
Comment
Question by:chrisryhal
  • 6
  • 3
12 Comments
 
LVL 6

Expert Comment

by:sara110
ID: 17986777
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
http://www.vb-helper.com/howto_net_datagrid.html
0
 
LVL 6

Expert Comment

by:sara110
ID: 17986817
0
 
LVL 2

Author Comment

by:chrisryhal
ID: 17986848
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.
0
 
LVL 6

Accepted Solution

by:
sara110 earned 500 total points
ID: 17986908
vb.net example
http://www.codeproject.com/vb/net/grid101.asp

  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

0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 6

Expert Comment

by:sara110
ID: 17986915
the first example in vbhelper is very simple one
0
 
LVL 2

Author Comment

by:chrisryhal
ID: 17986921
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=;" & _
  "Password="

    ' 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
        data_adapter.Fill(m_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(command_builder.GetInsertCommand.CommandText)
            Debug.WriteLine("*** UPDATE ***")
            Debug.WriteLine(command_builder.GetUpdateCommand.CommandText)
            Debug.WriteLine("*** DELETE ***")
            Debug.WriteLine(command_builder.GetDeleteCommand.CommandText)

            ' Save the changes.
            data_adapter.Update(m_DataSet)
        End If
    End Sub
0
 
LVL 6

Expert Comment

by:sara110
ID: 17986969
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
        Try
           
            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
            cnn.Open()
            cmdUpdate.ExecuteNonQuery()
            cnn.Close()
            Return True
        Catch ex As Exception
            cnn.Close()
            Return False
        End Try
    End Function

0
 
LVL 2

Author Comment

by:chrisryhal
ID: 17987038
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.
0
 
LVL 6

Expert Comment

by:sara110
ID: 17987083
I haven't used this class yet  but this is microsoft reference:
http://msdn2.microsoft.com/en-us/library/system.data.oledb.oledbschemaguid.aspx
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
Hi friends,  in this video  I'll show you how new windows 10 user can learn the using of windows 10. Thank you.

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now