2012-02-14 2 views
1

SQL 데이터베이스에 데이터를 삽입하는 응용 프로그램을 만들었습니다. 기본적으로 기본 폼에서 사용자는 데이터베이스로 이동할 데이터를 묻는 두 번째 양식을 엽니 다. 윈도우가 닫혀,양식을 닫은 후 SQL 새로 고침

 private void submitButton_Click(object sender, EventArgs e) 
     { 
//Get form values 
       try 
       { 
//Open test connection 
       } 
       catch (Exception ex) 
       { 
//Handle errors 
       } 
       finally 
       { 
//Close test connection 
       } 

       //Run the SQL statements 
       try 
       { 
//Inser SQL data 
       } 
       catch (Exception ie) 
       { 
//Handle errors 
       } 
       finally 
       { 
        //Close the connection 
        if (conn.State != ConnectionState.Closed) 
        { 
//Close the connection 
        } 
        //Close the window 
        this.Close(); 
        //Tell the main form to reload SQL data (not working) 
        mainForm firstForm; 
        firstForm = new mainForm(); 
        firstForm.refreshCall(); 

       } 

      } 
     } 

그러니까 기본적으로, 사용자가 (submitButton) OK 안타 데이터를 삽입하고, refreshCall() 메소드가 호출됩니다 : 코드는 다음과 같습니다. 내 방법 'refreshCall'는 다음과 같이 기본 폼에 출력되는 SQL 데이터를 갱신하도록되어 :

public void refreshCall() 
{ 
    SqlConnection conn = new SqlConnection("Data Source=SERVER\\SQL_DB;Initial Catalog=dataTable;Integrated Security=True"); 
    try 
    { 
     conn.Open(); 
     DataSet ds = new DataSet(); 
     SqlDataAdapter adapter = new SqlDataAdapter("SELECT part_num from dbo.Parts", conn); 
     adapter.Fill(ds); 
     this.listParts.DataSource = ds.Tables[0]; 
     this.listParts.DisplayMember = "part_num"; 
     conn.Close(); 
    } 
    catch (SqlException odbcEx) 
    { 
     MessageBox.Show("There was an error connecting to the data source.\nError Code: 1001", "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
    } 

} 

그러나,이 메서드가 호출 될 때, 데이터는 I가 의미하는 유엔 갱신 남아 응용 프로그램을 닫고 다시로드하여 변경 사항을 확인하십시오. SQL 데이터를 변경하지 않고 코드에서 잘못 처리하고 있습니까? 이 작업을 수행하는 더 좋은 방법이 있습니까? 폼이 초기화 될 때 refreshCall에서 똑같은 코드를 사용하여 데이터를로드한다는 것은주의해야합니다.

도움을 주시면 감사하겠습니다.

+2

디버거를 단계별로 - 새로 고침 호출하기 전에 SQL 삽입 코드를 호출되고? 또한 - 당신은 SQL 삽입 코드를 게시 할 수 있습니까? 연결/트랜잭션이 올바르게 완료되었을 수 있습니다 .... – tsells

답변

3

두 번째 양식은 기본 양식의 새 인스턴스를 만드는 것으로 보입니다. 새 인스턴스가 표시되지 않습니다. refreshCall에 대한 기존 기본 양식을 가져와야합니다.

+0

어떻게 새 양식을 작성하는 대신 기존 양식에서 refreshCall을 호출하게합니까? –

+0

완전히 새로운 인스턴스를 만드는 데 그리워 - 좋은 캐치 ... – tsells

1

두 번째 폼을 열면 기본 폼에 다음 코드를 사용할 수 있습니다. 당신의 마지막 블록의

두 번째 형태로 다음
// the ShowDialog will open your second form and then you use your DialogResult 
// from the second form to tell your main form to refresh the data 
yourSecondForm openSecondForm = new yourSecondForm.ShowDialog(); 
if(openSecondForm.DialogResult == DialogResult.OK) 
{ 
    refreshCall() 
} 

는 :

finally 
{ 
    //Close the connection 
    if (conn.State != ConnectionState.Closed) 
    { 
     //Close the connection 
    } 
    //Close the window 
    DialogResult = DialogResult.OK; 
}