2017-12-21 12 views
0

사용자가 드롭 다운 목록에서 선택하고 API를 쿼리 한 다음 데이터가있는 SQL Server 테이블을 채우는 단추를 누르는 콤보 상자가있는 Windows 양식이 있습니다. 데이터 서식을 지정하고 datagridview에 3 개의 필드를 표시하십시오. 그런 다음 사용자는 데이터를 삭제하거나 CSV로 내보낼 수 있습니다.DataTable이 최신 데이터로 업데이트되지 않음

이 프로세스는 한 번 실행하면 완벽하지만 두 번째 정보 집합을 CSV로 내보내려고하면 C# variables/datatable가 첫 번째 실행에서 정보를 유지합니다. (필자는 서버 측에 모든 것이 채워져 있는지 확인했습니다.)

코드를 단계별로 실행하고 디버그하고이 코드 줄 Form1.dtEmpNames = Form1.allEmps.DefaultView.ToTable(true, "Name");이 선택된 새 이름으로 업데이트되지 않는다는 사실을 확인했습니다. 그것은 첫 번째 이름을 유지합니다. 멀리 컴퓨터에서이 안된하고,보다 의미있는 DataTable의 이름을 사용하지만,이 적어도 그런 일을하는 예를 제공해야하므로

namespace Be1ng 
{ 
    public partial class Form1 : Form 
    { 
     public static DataTable allEmps = new DataTable(); 
     public static DataTable dtEmpNames = new DataTable(); 

     public void btnPush_Click() 
     { 
      allEmps.Clear(); 

      string query = "Select * from test"; 
      SqlConnection conn = new SqlConnection(@"Data Source=Server info;Initial Catalog=DB;User Id=user;Password=pwd;"); 
      conn.Open(); 
      SqlCommand cmd = new SqlCommand(query, conn); 
      SqlDataAdapter sda = new SqlDataAdapter(cmd); 
      sda.Fill(allEmps); 
      conn.Close(); 
      Form2 f2 = new Form2(); 
      f2.ShowDialog(); 
     } 
    } 
} 
namespace Be1ng 
{ 
    public partial class Form2 : Form 
    { 
     Private void Form2_Load(object sender, EventArgs e) 
     { 
      Form1.dtEmpNames = Form1.allEmps.DefaultView.ToTable(true, "Name"); 
     } 
    } 
} 

답변

1

...

//Form1 - declare the DataTable in the method and pass it to Form2 load 
public void btnPush_Click() 
{ 
    DataTable allEmps = new DataTable(); 
    //Query your server here 
    conn.Close(); 

    //pass the datatable in the call for the form 
    Form2 f2 = new Form2(allEmps); 
    f2.ShowDialog(); 
} 

//Then in the form2 load create a new constructor that accepts the DataTable 
    private DataTable dtpassed = new DataTable(); 
    private DataTable dtallemps = new DataTable(); 

    public Form2(DataTable allemps) 
    { 
     dtallemps = dtpassed; 
     InitializeComponent(); 
    } 
    private void Form2_Load(object sender, EventArgs e) 
    { 
     dtallemps = dtpassed.DefaultView.ToTable(true, "Name"); 
    }