我已经动态创建了数组CheckBoxes
,如果在Panel
中没有选择它们,我想进行正确的验证,但如果我继续使用for
循环,{{ 1}}继续出现。
任何人都可以帮我找到更好的方法吗?我只是想检查是否在Panel内检查了一个复选框控件,如果没有,则显示一个MessageBox
,它会说“选择一个复选框!”只有 ONCE 。
messagebox
for (int z = 0; z <= dataGridView.Columns.Count - 1; z++)
{
chk[z] = new CheckBox();
chk[z].Name = dataGridView.Columns[z].Name;
chk[z].Text = dataGridView.Columns[z].Name;
chk[z].AutoCheck = true;
chk[z].Bounds = new Rectangle(10, 20 + padding + dynamicHeight, 40, 22);
chk[z].Location = new Point(0, dynamicHeight);
chk[z].Size = new Size(120, 21);
panelCol.BackColor = Color.White;
//MessageBox.Show(chk[z].Name + "" + dataGridView.Columns[z].Name);
panelCol.Controls.Add(chk[z]);
//panelCol.AutoScrollMinSize = new Size(0, 100);
dynamicHeight += 20;
panelCol.Size = new Size(120, dynamicHeight);
}
btnValidate.MouseClick += (s, e) => //btnValidate Event
{
for (int z = 0; z < dataGridView.Columns.Count - 1; z++ )
{
if(chk[z].Checked == true)
{
ValidateCheck(dataGridView, chk);
}
else if(chk[z].Checked == false)
{
MessageBox.Show("Select a CheckBox!");
}
}
};
答案 0 :(得分:2)
这里是从Panel获取所有Checkbox的另一种方法,它们被检查(使用Linq):
List<CheckBox> selectedItems = panelCol.Controls.OfType<CheckBox>().Where(chk => chk.Checked).ToList();
答案 1 :(得分:1)
请更改以下验证方法,
public List<CheckBox> GetSelectedItems()
{
List<CheckBox> selectedList = new List<CheckBox>();
foreach(Control control in panelCol.Controls) // panelCol is your panel
{
if(control is CheckBox)
{
CheckBox chkCtrl = control as CheckBox;
if(chkCtrl.Checked)
{
selectedList.Add(chkCtrl);
}
}
}
return selectedList;
}
btnValidate.MouseClick += (s, e) =>//btnValidate Event
{
List<CheckBox> selectedItems = GetSelectedItems();
if(selectedItems.Count == 0)
MessageBox.Show("Select a CheckBox!");
else{
// Continue with other validation for the selected checkboxes from the list
}
}
希望它有所帮助!