2011-10-07 113 views
2

我有一個MyControl類。在MyClass對象裏面有文本框和複選框。複選框事件處理

我想添加一個複選框事件處理程序,但它不起作用。可能是什麼問題?

private List<MyControls> _myControls = new List<MyControls>(); 
MyControls mc = new MyControls(); 

public void CreateFormElements(int i, StringReader sr) 
{ 
    ProductForm form2 = new ProductForm(); 
    form2.Visible = true; 
    form2.Activate(); 
    String line = ""; 

    for (int n = 0; n < i; n++) 
    { 
     line = sr.ReadLine(); 
     mc = new MyControls(); 

     if (line.Length > 3) 
     { 
      String[] _line = line.Split(new char[] { '\t' }); 
      mc.SetY(30 + n * 20); 
      mc.initElements(_line, n); 
      _myControls.Add(mc); 
      **mc.cb.CheckedChanged += cb_CheckedChanged;** 
     } 
    } 
} 


private void cb_CheckedChanged(Object sender, EventArgs e) 
{ 
    string NameSet = (sender as CheckBox).Name.Split(new char[]{'_'})[1]; 
    MessageBox.Show(NameSet); 
} 

這裏是MyControls類代碼:

class MyControls 
{ 
    int x=5; 
    int y=30; 
    public CheckBox cb = new CheckBox(); 
    public TextBox tb1 = new TextBox(); 

    public TextBox tbSpecs = new TextBox(); 
    public TextBox tb3 = new TextBox(); 
    public TextBox tb4 = new TextBox(); 

    public void initElements(String[] name, int i) 
    { 
     cb.Width = 10; 
     cb.Height = 10; 
     cb.Name = "cb_" + i.ToString(); 
     cb.Location = new Point(x, y+5); 
     cb.Checked = false; 
     Form.ActiveForm.Controls.Add(cb); 

     x += 15; 

     tb1.Width = 50; 
     tb1.Height = 20; 
     tb1.Location = new Point(x, y); 
     tb1.Name = "tb1_" + i.ToString(); 
     tb1.Text = name[0]; 
     Form.ActiveForm.Controls.Add(tb1); 
     x += 60; 

     tbSpecs.Width = 150; 
     tbSpecs.Height = 20; 
     tbSpecs.Name = "tb2_" + i.ToString(); 
     tbSpecs.Text = name[1]; 
     tbSpecs.Location = new Point(x, y); 
     Form.ActiveForm.Controls.Add(tbSpecs); 
     x += 160; 

     tb3.Width = 40; 
     tb3.Height = 20; 
     tb3.Name = "tb3_" + i.ToString(); 
     tb3.Text = name[2]; 
     tb3.Location = new Point(x, y); 
     Form.ActiveForm.Controls.Add(tb3); 
     x += 50; 

     tb4.Width = 450; 
     tb4.Height = 20; 
     tb4.Name = "tb4_" + i.ToString(); 
     tb4.Text = name[3]; 
     tb4.Location = new Point(x, y); 
     Form.ActiveForm.Controls.Add(tb4); 

     x = 0; 
    } 

    public int SetX(int X) 
    { 
     x = X; 
     return x; 
    } 

    public int SetY(int Y) 
    { 
     y = Y; 
     return y; 
    } 
} 
+0

什麼是MyControls? –

+3

定義「它不起作用」。 – David

+0

MyControls.cs是一個類。它擁有4個文本框和1個複選框。我現在添加它 –

回答

3
mc.cb.CheckedChanged += new System.EventHandler(this.cb_CheckedChanged) 
+0

您不能直接分配委託,但必須通過EventHandler。 –

+1

就我所知,編譯器會隱式地爲你做這件事。 – Joey

+0

+1指向我在正確的方向 – Enrico

0

幾點要在CreateFormElements(int i, StringReader sr){...}檢查:

i大於零?如果沒有,循環將永遠不會運行,並且事件處理程序將永遠不會被連接。

line.Length是否大於零?如果沒有,你永遠不會進入if塊,處理程序不會被連接。

+0

問題解決Joey現在感謝我得到了另一個問題:)很快我會發布它。我需要更改文本框的位置... –