如何在没有刷新按钮的情况下刷新datagridview?

时间:2013-10-02 12:53:05

标签: vb.net

如何在添加或删除后自动刷新并查看新的当前数据网格视图? 我应该在“msgbox”之后添加什么代码来查看当前数据?

Private Sub add()
    Dim conn As New OleDbConnection
    Dim cmd As New OleDbCommand
    Dim sSQL As String = String.Empty
    Try
        conn = New OleDbConnection(Get_Constring)
        conn.Open()
        cmd.Connection = conn
        cmd.CommandType = CommandType.Text
        sSQL = "INSERT INTO course ( code,  description)"
        sSQL = sSQL & " VALUES (@cod, @des)"
        cmd.CommandText = sSQL
        cmd.Parameters.Add("@cod", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txtcode.Text)) > 0, Me.txtcode.Text, DBNull.Value)
        cmd.Parameters.Add("@des", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txtdescription.Text)) > 0, Me.txtdescription.Text, DBNull.Value)
        cmd.ExecuteNonQuery()
        MsgBox("Data has been save.")

        conn.Close()
    Catch ex As Exception
        MessageBox.Show("Already exist")
    End Try
End Sub

1 个答案:

答案 0 :(得分:0)

您应该将DataGridView绑定到适当的DataSource,例如DataTable

然后,您可以使用SqlDataAdapterDataTable绑定DataGridView,而不是在数据库中手动插入数据。

这是一个简单的例子:

Dim cons = New SqlConnectionStringBuilder() With 
    { 
                .DataSource = "your_server", 
                .InitialCatalog = "your_db",
                .UserID = "your_user", 
                .Password = "your_password" 
    }.ConnectionString

Dim con = New SqlConnection(cons)
con.Open()

' create a SqlDataAdapter and provide the SELECT command '
Dim adapter = New SqlDataAdapter()
Dim cb = New SqlCommandBuilder(adapter)
adapter.SelectCommand = New SqlCommand("SELECT code, description FROM course", con)
' the INSERT command can be generated '
adapter.InsertCommand = cb.GetInsertCommand()

' fill a new DataTable with data from database '
Dim dt = New DataTable()
adapter.Fill(dt)

' create a Form with DGV and Insert-Button '
Dim f = New Form()
Dim dgv = New DataGridView() With 
{ 
    .DataSource = dt,
    .Dock = DockStyle.Fill
}

Dim addButton = New Button() With 
{
    .Text = "Add new",
    .Dock = DockStyle.Bottom
}

Dim i = 0
AddHandler addButton.Click, Function(s, o) 
                                ' we insert the new data directly into the DataTable '
                                dt.Rows.Add(New Object() {"Some","Text"})
                                ' and let the SqlDataAdapter handle the insert '
                                adapter.Update(dt)
                            End Function

f.Controls.Add(addButton)
f.Controls.Add(dgv)
f.ShowDialog()

由于新数据直接写入DataTableDataGridView会立即更新。

当然,使用TableAdapters时,这会更容易。