关于对象引用的一个例子.注意不要和对象名字符串相混淆. 前提:假设有n个checkBox控件.验证checkBox 是否被选择.用for来实现.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; //自己添加上去的.因为要用到里面的ArrayList类
namespace autorun { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { ArrayList checkboxArray=new ArrayList(); checkboxArray.Add(checkBox1); //此处添加的是控件引用而不是字符串 checkboxArray.Add(checkBox2); checkboxArray.Add(checkBox3); checkboxArray.Add(checkBox4); checkboxArray.Add(checkBox5); checkboxArray.Add(checkBox6); checkboxArray.Add(checkBox7); checkboxArray.Add(checkBox8); checkboxArray.Add(checkBox9); checkboxArray.Add(checkBox10); for(int i=0;i { CheckBox checkBoxTest = (CheckBox)checkboxArray[i]; //提取时一定要进行强制类型转换 if (checkBoxTest.Checked == true) { ........ } } } } }
若从组表中提取对象时不进行类型转换会出现如下错误: Cannot implicitly convert type 'object' to 'System.Windows.Forms.CheckBox'. An explicit conversion exists (are you missing a cast?)
特别感谢 CSDN ID:3000sunqin(3000suqnin)
JasonHeung(拥有一切不过就这样笑着哭)仁兄给出的另一种方法.目前尚未调试通过
for (int i = 0; i < this.Controls.Length; i++) { if (this.Controls[i].GetType() = typeof(CheckBox) && ((CheckBox)this.Controls[i]).Checked = true) { .............. } }
|