复选框事件处理
本文关键字:事件处理 复选框 | 更新日期: 2023-09-27 18:10:36
我有一个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;
}
}
mc.cb.CheckedChanged += new System.EventHandler(this.cb_CheckedChanged)
CreateFormElements(int i, StringReader sr){...}
的几点检查:
i
是否大于零?如果不是,循环将永远不会运行,事件处理程序将永远不会被附加。
line.Length
是否大于零?如果没有,你将永远无法进入If块,处理程序也不会被附加。