Thursday, May 2, 2013

Save & Update Data into SQL Table through VB.Net Datagridview



Private Sub SaveButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Try
            con = New SqlConnection(Module1.mod1)
            con.Open()
            i = Me.DataGridView1.Rows.Count
            While (x <= i - 1)
                sql = "Insert into abc values('" & Me.DataGridView1.Item(0, x).Value & "','" & Me.DataGridView1.Item(1, x).Value & "'," & _
                "'" & Me.DataGridView1.Item(2, x).Value & "','" & Me.DataGridView1.Item(3, x).Value & "')"
                cmd = New SqlCommand(sql, con)
                icount = cmd.ExecuteNonQuery
                x = x + 1
            End While
            MsgBox("SAVE OK")
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        con.Close()
        Me.DataGridView1.Columns.Clear()
       End Sub

Private Sub ShowButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim dt As New DataTable
        dt.Clear()
        Try
            con = New SqlConnection(Module1.mod1)
            con.Open()
            sql = "SELECT * FROM ABC"
            da = New System.Data.SqlClient.SqlDataAdapter(sql, con)
            da.Fill(dt)
            DataGridView1.DataSource = dt
            Me.DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        con.Close()
    End Sub

Private Sub UpdateButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        Try
            con = New SqlConnection(Module1.mod1)
            con.Open()
            i = DataGridView1.CurrentRow.Index
            sql = "Update abc set address = '" & DataGridView1.Item(1, i).Value & "', date = '" & DataGridView1.Item(2, i).Value & "', " & _
            "chk = '" & DataGridView1.Item(3, i).Value & "' where name = '" & DataGridView1.Item(0, i).Value & "'"
            cmd = New SqlCommand(sql, con)
            icount = cmd.ExecuteNonQuery
            MsgBox("UPDATE OK")
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        con.Close()
        End Sub