2013-10-02 2 views
0

추가하거나 삭제 한 후 새 현재 데이터 그 룹뷰를 자동으로 새로 고치고 볼 수 있습니까? 현재 데이터를 보려면 "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에, 예를 들어, a DataTable.

그런 다음 데이터베이스에 수동으로 데이터를 삽입하는 대신 SqlDataAdapterDataTableDataGridView을 사용할 수 있습니다. 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() 

:

여기 간단한 예이다.

물론 TableAdapters을 사용하면이 방법이 훨씬 쉽습니다.

관련 문제