如何从动态创建的复选框中获得选定的值?



我从数据库动态添加CheckBox控件到FlowLayOutPanel。我如何获取和存储所有选定的值?

我的示例代码在这里…

private void dynamicCheck()
{
//throw new NotImplementedException();
DataSet1TableAdapters.tbl_subjects1TableAdapter ta = 
new DataSet1TableAdapters.tbl_subjects1TableAdapter();
DataTable dt = ta.GetData();
foreach (DataRow row in dt.Rows)
{
CheckBox chk = new CheckBox();
chk.Width = 90;
chk.Text = row[1].ToString();
chk.CheckedChanged += new 
EventHandler(changeCheck);
flowLayoutPanel1.Controls.Add(chk);            
}
}   
private void changeCheck(object sender, EventArgs e)
{
//throw new NotImplementedException();
CheckBox chk = sender as CheckBox;
if (chk.Checked)
{
//MessageBox.Show("checked item" + chk.Text);        
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
}

我会这样做:

private List<CheckBox> _checkBoxes = null;
private void DynamicCheck()
{
DataSet1TableAdapters.tbl_subjects1TableAdapter ta =
new DataSet1TableAdapters.tbl_subjects1TableAdapter();
DataTable dt = ta.GetData();

_checkBoxes = dt.Rows.Cast<DataRow>().Select(row =>
{
CheckBox chk = new CheckBox();
chk.Width = 90;
chk.Text = row[1].ToString();
chk.CheckedChanged += new EventHandler(changeCheck);
flowLayoutPanel1.Controls.Add(chk);
return chk;
}).ToList();
}

现在您可以访问_checkBoxes中的每个CheckBox

相关内容

  • 没有找到相关文章

最新更新