2012-07-04 2 views
0

저는 Winforms에서 데이터베이스에 데이터를 추가, 삭제 및 업데이트합니다. 나는 모든 추가, 삭제 및 업데이트 양식에 대한 gridview 있습니다. "삭제"버튼을 클릭하면 레코드를 삭제 한 후 삭제 된 레코드는 즉시 dataGridView에서 제거되어야합니다.데이터베이스에 항목을 추가하거나 삭제할 때 dataGridView 항목 새로 고침?

//// DATABIND는 사용 또는 어셈블리 참조 누락 오류가 발생합니다. 뒤에

코드 :

private void btnDelete_Click(object sender, EventArgs e) 
    { 

     if (txtIDD.Text == "") 
     { 
      MessageBox.Show("Please fill ID no. of record to Delete", "Important Message"); 

     } 
     else 
     { 
      try 
      { 
       OleDbCommand Cmd = new OleDbCommand(); 
       Cmd.Connection = conn; 
       conn.Open(); 
       Cmd.CommandText = "DELETE FROM AddressBook WHERE ID="+txtIDD.Text; 
       Cmd.CommandType = CommandType.Text; 
       Cmd.ExecuteNonQuery(); 
       Cmd.Connection.Close(); 
       conn.Close(); 
       dataGridView3.Update(); 
       MessageBox.Show("Delete Succesfull"); 
      } 
      catch (System.Exception err) 
      { 
        dataGridView3.DataSource = dt; 
        dataGridView3.DataBind(); 
        dataGridView3.Update(); 

       this.label27.Visible = true; 
       this.label27.Text = err.Message.ToString(); 
      } 
     } 

    } 
+0

이 코드는 SQL 삽입에 취약합니다 – JohnnBlade

+0

개인적인 의견이지만 격자에 다 내가 삭제해야 할 논리를 바꿀 것입니다 : 사용자가 텍스트를 입력하고, 그리드의 관련 레코드를 검색하고, db에서 삭제를 실행 한 후, gird에서 레코드를 직접 제거하거나 기본 바인딩 된 데이터 소스. (추가 된 장점은 선택한 행에 직접 삭제 작업을 수행 할 수 있다는 것입니다) –

답변

0

바인드 다시 그리드는 값이 데이터베이스 후에는 그리드를 다시로드 할 수있다 함수 만들기 등

private void btnDelete_Click(object sender, EventArgs e) 
{ 

    if (txtIDD.Text == "") 
    { 
     MessageBox.Show("Please fill ID no. of record to Delete", "Important Message"); 

    } 
    else 
    { 
     try 
     { 
      OleDbCommand Cmd = new OleDbCommand(); 
      Cmd.Connection = conn; 
      conn.Open(); 
      Cmd.CommandText = "DELETE FROM AddressBook WHERE ID="+txtIDD.Text; 
      Cmd.CommandType = CommandType.Text; 
      Cmd.ExecuteNonQuery(); 
      Cmd.Connection.Close(); 
      conn.Close();     

      **//Call a method that binds the grid or get DataTable from database and bind it like this** 
      dataGridView3.DataSource = dt;    
      dataGridView3.Update(); 

      MessageBox.Show("Delete Succesfull"); 
     } 
     catch (System.Exception err) 
     { 
      this.label27.Visible = true; 
      this.label27.Text = err.Message.ToString(); 
     } 
    } 
} 
+0

안녕하세요, 저는 Windows 애플리케이션을 만들고 있습니다. Databind()가 작동하지 않습니다. (사용 또는 어셈블리 참조가 없음을 알리는 오류가 발생합니다. –

+0

DataBind()를 제거하면 데이터 소스를 할당 할 수 있지만 데이터 소스에 할당하기 전에 최신 데이터를 가져옵니다. – Adil

+0

업데이트 된 데이터를 가져 오는 데 함수를 사용했습니다. :)))) 잘 작동 –

-2

을 추가, 업데이트 및 삭제할 형성 가져

private method ReloadGrid() 
{ 
    // first load your datatable/dt then set it as the datasource of your grid 
    dataGridView3.DataSource = dt; 
    dataGridView3.DataBind(); 

} 
관련 문제