2013-11-23 46 views
0

如何從另一個類將數據追加到窗體上的dataGridView?將數據添加到另一個類的窗體上的gridView

這裏是類:

class TermSh 
    { 

     public HttpWebRequest request_get_page_with_captcha; 
     public HttpWebResponse response_get_page_with_captcha; 
     public string url; 
     public Form1 form1; 
     public BindingSource bindingSource1 = new BindingSource(); 
     public int id = 0; 



     public TermSh(Form1 form1) 
     { 
      this.form1 = form1; 
      form1.dataGridView1.DataSource = bindingSource1; 
     } 

     public void somemethod() 
     { 
      try 
      {     

       cookies += response_get_page_with_captcha.Headers["Set-Cookie"]; 


       bindingSource1.Add(new Log(id++, DateTime.Now, cookies)); 
       form1.dataGridView1.Update(); 
      } 
      catch (Exception e) 
      { 
       MessageBox.Show(e.Message); 
      } 
     } 

和窗體類:

TermSh term_sh = new TermSh(this); 
term_sh.somemethod(); 

什麼,我做錯了什麼?爲什麼在代碼執行後我的datagridview是空的,但是通過調試我發現,bindingSource1不是空的。 如何添加數據?

回答

3

我認爲,你要實現目標的方式是不正確的。首先,我認爲傳遞Form類到一個類是非常非常糟糕的。然後你可以簡單地操作一個列表並返回值並在你的Form中使用這個值(列表)。

我認爲最好這樣做: [編輯1]這下面的類,是你的ptimary類有一個方法,這個方法返回一個新的日誌,你可以添加這個返回值到datagridview在Form1上。

class TermSh 
{ 

    public HttpWebRequest request_get_page_with_captcha; 
    public HttpWebResponse response_get_page_with_captcha; 
    public string url; 
    public int id = 0; 

    public List<Log> somemethod() 
    { 
     try 
     {     

      cookies += response_get_page_with_captcha.Headers["Set-Cookie"]; 

      return new Log(id++, DateTime.Now, cookies); //use this return value in your Form and update datagridview 
     } 
     catch (Exception e) 
     { 
      MessageBox.Show(e.Message); 
     } 
    } 
} 

[EDIT 2]之後:必須準備登錄類被用作在的BindingSource(Form1.bindingSource)的集合和更新的GridView。和下面的代碼顯示Log類:

class Log 
{ 
    private int id; 
    private DateTime datetime; 
    private string log_text; 

    public Log(int id, DateTime datetime, string log_text) 
    { 
     this.id = id; 
     this.datetime = datetime; 
     this.log_text = log_text; 
    } 

    #region properties 
    public int ID { get { return id; } set { id = value; } } 
    public DateTime DATE_TIME { get { return datetime; } set { datetime = value; } } 
    public string LOG_TEXT { get { return log_text; } set { log_text = value; } } 
    #endregion 
} 

[編輯3],並將該代碼在Form1,使用類TermSh的返回值,並填充在DataGridView:

​​

[EDIT 4 ]所以如果你有一個問題:「如何使用這個類作爲bindingSource中的集合??」。很簡單,你可以用對象填充一個dataGridView:this article很有幫助。

+0

以及如何不將表單類傳遞給另一個類? –

+0

另外:那麼你可以簡單地操作一個列表並返回值並使用這個值......如何? –

+0

代碼不清楚嗎? – mostafa8026

相關問題