DataGridView Trouble

kcwallace

Centurion
Joined
May 27, 2004
Messages
175
Location
Austin, TX
Is there a tutorial that will show me how to bind a DataGridView to a dataset that is linked to a database, and successfully update the records. I cannot seem to figure out how to make a UpdateCommand work successfully. I am using VS 2005 and VB.Net

THe code below is my attempt. I am unsure how to actually force an update

Visual Basic:
Public Class EmulsionAgeData
    Private Cnn As New SqlConnection(myconnectionstring)
    Private Cmd As New SqlCommand
    Private DS As New DataSet
    Private DA As New SqlDataAdapter
    Private UCmd As New SqlCommand

    Private Sub EmulsionAgeData_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        With Cmd
            .Connection = Cnn
            .CommandType = CommandType.Text
            .CommandText = "SELECT * FROM EmulsionData ORDER BY EmulID"
        End With
        Cnn.Open()
        DA.SelectCommand = Cmd
        DA.Fill(DS)
        DataGridView1.DataSource = DS
        DataGridView1.DataMember = DS.Tables(0).TableName

        UCmd.CommandText = "UPDATE EmulsionData SET EmulID=@Emul, StartDate=@Sdate, StartOD=@SOD WHERE EmulID=@Emul"
        UCmd.Connection = Cnn
        UCmd.CommandType = CommandType.Text
        UCmd.Parameters.Add("@Emul", SqlDbType.NVarChar, 3)
        UCmd.Parameters.Add("@SDate", SqlDbType.DateTime)
        UCmd.Parameters.Add("@SOD", SqlDbType.Float)
        
        DA.UpdateCommand = UCmd
    End Sub
End Class
 
TableAdapter

Sorry...just realized you were writing a Windows Forms application and not an ASP.NET application:o . You should take a look at TableAdapters (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvs05/html/tableadapters.asp) instead.

Todd

Take a look at the DataSource controls (such as the System.Web.UI.WebControls.SqlDataSource). Using the GridView/DataSource combination is so much easier than using the GridView/DataSet/DataAdapter combination.

Here is an MSDN article on them: http://msdn.microsoft.com/asp.net/reference/data/default.aspx?pull=/msdnmag/issues/04/08/gridview/default.aspx

Todd
 
Last edited:
I'm surprised nobody has replied to this topic yet. I don't have much experience dealing with databases as the only data centric applications I've made have used XML to store data. But what I have found is that objects which employ a DataSource property generally don't update at the same time as the the actual DataSource object. Is this the problem you are encountering? The way I've normally got around this in the past is to set the DataSource property to null and then back to the DataSource object. Doing this after every update to the DataSource ensures both sets are synchronised.
 
Back
Top