如何使用datagridview在sql数据库中添加数据

时间:2015-09-02 08:56:40

标签: sql vb.net datagridview

继承我的代码,将数据添加到sql数据库

Dim ConStr As String = "Data Source=SYSTEMS-LAPTOP\DEVSQL;Initial Catalog=ContactDB;Persist Security Info=True;User ID=sa;Password=P@ssw0rd123"
Dim sql As String = "SELECT * FROM dataContactDB"
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

此代码从sqldatabase

加载datagridview中的数据
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    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, "dataContactDB")
    sqlTable = sqlDataset.Tables("dataContactDB")
    sqlCon.Close()
    dgData.DataSource = sqlDataset.Tables("dataContactDB")
    dgData.ReadOnly = True
    dgData.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub

将数据添加到sqldatabase

的代码
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
    sqlCon.Open()
    sqlCmd.CommandText = "insert into dataContactDB(con_Name,con_Phone,Address,Company,Gender) values('" & txtName.Text & "','" & txtPhone.Text & "','" & txtAddress.Text & "','" & txtCompany.Text & "','" & txtGender.Text & "')"
    sqlCmd.ExecuteNonQuery()
    sqlCon.Close()

End Sub

我想要做的就是在sqldatabase中添加数据。 datagridview将检索新添加的数据并将其添加到其列表中。每次我添加数据。 datagridview没有显示我最近添加的数据,我该怎么做?

1 个答案:

答案 0 :(得分:0)

您只需在网格中重新加载数据即可。将所有代码放在名为LoadMyGrid的函数中,该函数已在frm_load中编写。现在从frm_load调用此方法。也可以在最后一行的按钮单击事件中调用相同的方法。