如何将数据插入SQL Server数据库并检索并放入datagridview?

时间:2015-08-31 02:45:05

标签: sql-server vb.net datagridview

我想要做的是,在将数据插入SQL Server数据库之后,datagridview将从数据库中检索添加的数据并将其添加到其行中。

我是vb.net的新手

我的对话框中的代码添加表单。我把它命名为dlgAdd

Imports System.Windows.Forms
Imports System.Data.SqlClient

Public Class dlgAdd
    Dim ConStr As String = "Data Source=SERVER008;Initial Catalog=CollectionDB;Persist Security Info=True;User ID=sa;Password=P@ssw0rd1234"
    Dim sql As String
    Dim sqlCon As New SqlConnection
    Dim sqlCmd As New SqlCommand
    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click    
        sql = "insert into dataCollection(CustomerName,OR_no,SOR_no,Balance,Cash_Amount,Check_Amount) values('" & txtName.Text & "','" & txtOR.Text & "','" & txtSOR.Text & "','" & txtBalance.Text & "','" & txtCash.Text & "','" & txtCheck.Text & "')"
        sqlCmd = New SqlCommand(sql, sqlCon)
        sqlCmd.ExecuteNonQuery()
        Me.DialogResult = System.Windows.Forms.DialogResult.OK
    End Sub

    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub dlgAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        sqlCon = New SqlConnection(ConStr)
        sqlCon.Open()
    End Sub
End Class

' here is my code in MainTrans form

dgMainData is my datagridview.

Imports System.Data
Imports System.Data.SqlClient

Public Class frmMainTrans
    Dim ConStr As String = "Data Source=SERVER008;Initial Catalog=CollectionDB;Persist Security Info=True;User ID=sa;Password=P@ssw0rd1234"
    Dim sql As String = "SELECT * FROM dataCollection"
    Dim sqlCon As New SqlConnection
    Dim sqlCmd As New SqlCommand
    Dim sqlAdapter As SqlDataAdapter
    Dim sqlBuilder As SqlCommandBuilder
    Dim sqlDataset As DataSet
    Dim sqlTable As DataTable
    Private Sub Getdata()
        sqlCon = New SqlConnection(ConStr)
        sqlCon.Open()
        sqlCmd = New SqlCommand(sql, sqlCon)
        sqlAdapter = New SqlDataAdapter(sqlCmd)
        sqlBuilder = New SqlCommandBuilder(sqlAdapter)
        sqlDataset = New DataSet
        sqlAdapter.Fill(sqlDataset, "dataCollection")
        sqlTable = sqlDataset.Tables("datacollection")
        sqlCon.Close()
        dgMainData.DataSource = sqlDataset.Tables("dataCollection")
        dgMainData.ReadOnly = True
        dgMainData.SelectionMode = DataGridViewSelectionMode.FullRowSelect
    End Sub
    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        dlgAdd.ShowDialog()
    End Sub
    Private Sub frmMainTrans_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Call Getdata()

    End Sub
End Class

0 个答案:

没有答案