如果我动态创建一个控件,如下所示
private void button10_Click(object sender, EventArgs e)
{
CheckedListBox CheckedListBox1 = new CheckedListBox();
CheckedListBox1.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(224)), ((System.Byte)(192)));
CheckedListBox1.ItemHeight = 16;
CheckedListBox1.Location = new System.Drawing.Point(12, 313);
CheckedListBox1.Name = "CheckedListBox1";
CheckedListBox1.Size = new System.Drawing.Size(168, 244);
CheckedListBox1.TabIndex = 0;
Controls.Add(CheckedListBox1);
Button button12 = new Button();
button12.Location = new Point(900, 500);
button12.Size = new Size(75, 23);
button12.Click += new System.EventHandler(button12_Click);
button12.Name = "button12";
button12.Text = "Toggle All";
Controls.Add(button12);
}
从本地范围之外的函数引用该控件的最佳方法是什么?是否最好创建一个静态类,以某种方式保存对可以在本地范围之外访问的控件的引用,或者是winforms的findcontrol函数(我认为findcontrol仅适用于web)。
我想要
private void button12_Click(object sender, EventArgs e)
{
for (int i = 0; i <= (CheckedListBox1.Items.Count - 1); i++)
{
if (CheckedListBox1.GetItemCheckState(i) == CheckState.Checked)
{
CheckedListBox1.SetItemCheckState(i, CheckState.Indeterminate);
}
else if (CheckedListBox1.GetItemCheckState(i) == CheckState.Indeterminate)
{
CheckedListBox1.SetItemCheckState(i, CheckState.Checked);
}
}
}
能够工作,但由于范围我出错了?请帮助新手
感谢
答案 0 :(得分:1)
我假设两个函数 button12_Click 和 button10_Click 是From类的成员。在这种情况下,您应该创建From类的 CheckListBox1 和 button12 成员。这样,button12_Click将能够引用您将创建的控件。
public partial class Form1 : Form
{
CheckedListBox CheckedListBox1 = null;
Button button12 = null;
private void button10_Click(object sender, EventArgs e)
{
CheckedListBox1 = new CheckedListBox();
CheckedListBox1.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(224)), ((System.Byte)(192)));
CheckedListBox1.ItemHeight = 16;
CheckedListBox1.Location = new System.Drawing.Point(12, 313);
CheckedListBox1.Name = "CheckedListBox1";
CheckedListBox1.Size = new System.Drawing.Size(168, 244);
CheckedListBox1.TabIndex = 0;
Controls.Add(CheckedListBox1);
button12 = new Button();
button12.Location = new Point(900, 500);
button12.Size = new Size(75, 23);
button12.Click += new System.EventHandler(button12_Click);
button12.Name = "button12";
button12.Text = "Toggle All";
Controls.Add(button12);
}
private void button12_Click(object sender, EventArgs e)
{
for (int i = 0; i <= (CheckedListBox1.Items.Count - 1); i++)
{
if (CheckedListBox1.GetItemCheckState(i) == CheckState.Checked)
{
CheckedListBox1.SetItemCheckState(i, CheckState.Indeterminate);
}
else if (CheckedListBox1.GetItemCheckState(i) == CheckState.Indeterminate)
{
CheckedListBox1.SetItemCheckState(i, CheckState.Checked);
}
}
}
}
答案 1 :(得分:0)
当只有一个CheckedListBox
时,使它成为一个类变量。但是当你总是只有一个CheckedListBox
时 - 为什么要动态创建它?
答案 2 :(得分:0)
如果您要将控件添加到页面的Controls集合中,那就去看看吧。如果您知道控件的索引,则可以通过该方式引用它。如果你将控件添加到某个容器的Control的集合(例如,一个面板),那么在那里寻找它