2012-03-30 1 views
1

저는 Mcdonalds의 제어판에서 클라이언트가 취하고 싶은 것을 으로 선택하고 있습니다. Windows Forms C#을 사용하여이 작업을 수행하고 있습니다. 내가 만든 제품은 이라는 클래스를 만들고 Form1.cs에서 데이터베이스에서 읽은 제품을 넣을 목록을 만들었습니다. 나는 이것을 수행하여 DataGrid에서 결과를 보여주었습니다. 제 문제는 제가 제품 을 선택한 다음 보내기 버튼을 클릭하면 데이터 그리드가 자동으로 새로 고쳐지지 않는다는 것입니다. 나는 프로그램을 닫아야하고 언제 내가 그것을 다시 볼 수있다.목록을 사용하여 데이터베이스에서 정보를 수집하는 경우 자동으로 데이터 그리드를 새로 고치는 방법은 무엇입니까?

내 질문에, 데이터 업데이트를 업데이트하는 방법을 알고 있습니까? 프로그램을 다시 시작 하시겠습니까?

덕분에 아주 많이, 내가 아래에있는 내 코드를 추가합니다!

을 [] My_windows_form 1

#
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using MySql.Data.MySqlClient; 


namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     MySqlConnection conn = new MySqlConnection();  
     String connectionString = "Server=127.0.0.1; Database=mydatabase; Uid=root; Pwd=;";  
     List<products> listproducts = new List<products>(); 

     public string product; 
     public string quantity; 


     public Form1() 
     { 
      InitializeComponent();    
      startConn(); 
     } 
     private void startConn() 
     { 
      try 
      { 
       conn.ConnectionString = connectionString; 
       conn.Open();     
       textBox3.Text= "Correct connection"; 
       //we call the function READ 
       read(); 
      } 
      catch (MySqlException) 
      { 
       textBox3.Text="An error has ocurred"; 
      } 
     }  
     public void read() 
     { 
      MySqlCommand instruccio = conn.CreateCommand(); 
      instruccio.CommandText = "Select * from products"; 
      MySqlDataReader search = instruccio.ExecuteReader(); 
      while (search.Read()) 
      { 
       products prod = new products(); 
       prod.IdProd = search["idProd"].ToString();      
       prod.Name = search["nomProd"].ToString(); 
       prod.Quantity = Int32.Parse(search["quantitat"].ToString()); 
       listproducts.Add(prod); 
      } 
      dataGridView1.DataSource = listproducts; 

      search.Close(); 
      search.Dispose(); 

     }  
     private void btnEnviar_Click(object sender, EventArgs e) //Button Send (Enviar in spanish) 
     { 
      try 
      {   
       //before updating the stock in database we query the total quantity of the product selected 
       MySqlCommand instruccio1 = connexio.CreateCommand();    
       instruccio1.CommandText = "Select quantitat from productes where `nomProd`='"+ this.product +"'";    
       MySqlDataReader read = instruccio1.ExecuteReader();    
       int result = 0;    
       while (read.Read()) 
       { 
        resultat=Int32.Parse(read["quantitat"].ToString());      
       } 
       read.Dispose(); 
       instruccio1.Dispose(); 

       if (this.quantity != 0) 
       {     
        if (result > this.quantity) 
        { 

        int difference = result - this.quantity; 
        MySqlCommand instruccio2 = conn.CreateCommand(); 
        instruccio2.CommandText = "UPDATE products set `quantitat`='" + this.difference + "' where products.nomProd='" + this.product + "'"; 
        instruccio2.ExecuteNonQuery();         
        conn.Close(); 
            startConn(); 
        textBox1.Text= ""; 
        textBox2.Text = ""; 
        this.quantity = ""; 
        this.product = "";        
       } 
       else 
       { 
        MessageBox.Show("There's no quantity.");     
       }    
      } 
      catch (Exception xe) 
      { 
       MessageBox.Show("",xe.Message); 
      }   
     } 
     private void btnEsborrar_Click(object sender, EventArgs e) //Erase button 
     { 
      this.quantity = ""; 
      this.product = ""; 
      this.aEnviar = 0; 
      textBox1.Text = quantity; 
      textBox2.Text = product; 
     } 

.... 
.... 

답변

0

당신이 할 수있는 것은 다음과 같다 :

  1. 은 타이머를 추가 컨트롤을 폼에 적용하고 Tick 이벤트를 발생시키려는 시간을 설정하면 Interval 속성에 밀리 초 단위로 입력됩니다. 이 이벤트의
  2. startConn 함수를 호출하십시오.

하고 그게 전부를, 아주 쉬운 :

당신의 read() 방법에서
+0

답장을 보내 주셔서 감사 드리며 말씀 드렸지만 노력하지 않았습니다. 다른 한편으로는 연결을 닫고 업데이트를 만든 직후에 startConn 함수를 호출하려했지만 작동하지 않았습니다. 무슨 일이 일어나고 있는지 모르겠다. ( – user1298984

+1

이 줄을 추가하려고 시도 : read() 메서드 내에서 listproducts = new 목록 (); " –

+0

매우 대단히 감사합니다. – user1298984

-1

전에
dataGridView1.DataSource = listproducts; 

당신이 원하는 때마다

dataGridView1.DataSource = null; 

이 그런 다음 startConn() 메서드를 호출하여 추가 할 수 있습니다.

+0

이 방법으로 그리드를 자동으로 업데이트하는 데 도움이 될 수 있습니까? –

+0

먼저이 기능을 사용하면 목록에 새 항목을 추가 할 필요없이 새 목록을 새로 만들 필요가 없습니다. 답. 만약 당신이 그의 질문에서 그가 정말로 달성 할 수없는 것을이 글에서주의 깊게 읽으면, 당신이 내 대답을주의 깊게 읽으면 나는 그에게 당신이 그에게 보여줄 사건일지도 모를 때마다 그의 startConn()을 부르라고 말했다. 나는이 코멘트 선생님과 함께 졸업했다. – Dummy01

+0

어쨌든 그는 그의 업데이트 이후 이미이 방법을 호출 한 이후로 startConn()을 다른 곳에서 호출 할 필요조차 없다. 분명히 그는 자신의 DataGrid에서 변경 사항을 볼 수 없었습니다. – Dummy01