locked
How to perform insert, update and delete operation on datagridview

    Question



  • currently i am working on a project in which i am using datagridview control.
    if I enter key value in cell than remaining data of that particular row fetch automatically from data base. how?
    how to delete as row in datagridview?
    how to update a row in datagridview?
    Saturday, April 11, 2009 12:42 PM

Answers

  • Code sample: Update (Insert/Update/Delete) data back into database (MS Access or SQL Server) from DataGridView
    http://social.msdn.microsoft.com/forums/en-US/Vsexpressvb/thread/5980181e-f666-4f0a-ab50-c4ebecf96f02/
    Prerequisites: DataGridView and Button1 on Form1.
                       The Primary Key is required in database table.

    Imports System.Data.OleDb
    
    Public Class Form1
    
        Dim myDA As OleDbDataAdapter
        Dim myDataSet As DataSet
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=|DataDirectory|\myDB.mdb")
            Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM Table1", con)
            con.Open()
            myDA = New OleDbDataAdapter(cmd)
            'Automatically generates DeleteCommand,UpdateCommand and InsertCommand for DataAdapter object   
            Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(myDA)
            myDataSet = New DataSet()
            myDA.Fill(myDataSet, "MyTable")
            DataGridView1.DataSource = myDataSet.Tables("MyTable").DefaultView
            con.Close()
            con = Nothing
        End Sub
    
        ' Save data back into database   
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Me.Validate()
            Me.myDA.Update(Me.myDataSet.Tables("MyTable"))
            Me.myDataSet.AcceptChanges()
        End Sub
    
    End Class
    Monday, April 13, 2009 9:17 AM

All replies