2013-10-02 73 views
0

如何在添加或刪除後自動刷新並查看新的當前datagridview? 我應該在「msgbox」之後放置什麼代碼來查看當前數據?如何刷新沒有刷新按鈕的datagridview?

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 

回答

0

你應該綁定你DataGridView到適當DataSource,例如一個DataTable

然後,您可以使用SqlDataAdapter和您的DataGridView綁定到的DataTable,而不是手動在數據庫中插入數據。

這裏有一個簡單的例子:

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() 

由於新的數據直接寫進DataTable,該DataGridView立即更新。

當您使用TableAdapters時,這當然更容易。