好的,这是我的问题。我为我创建的每个复选框分配值,并且只有在选中它们后才会尝试将它们放入列表框中。所以这是我到目前为止编写的代码,其中当单击按钮时,两个值都被写入列表框,无论是否被选中,我如何使其按照我的解释工作?
public Form1()
{
InitializeComponent();
btnOne.Click += btnOne_Click;
chckOne.CheckedChanged += chckOne_CheckedChanged;
chckTwo.CheckStateChanged += chckTwo_CheckStateChanged;
}
void btnOne_Click(object sender, EventArgs e)
{
lstOne.Items.Add(number1 + number2);
}
string number1 = "ONE", number2 = "TWO";
void chckOne_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = new CheckBox();
if (chk.Checked == true)
{
lstOne.Items.Add(number1);
}
}
void chckTwo_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = new CheckBox();
if (chk.Checked == true)
{
lstOne.Items.Add(number2);
}
}
答案 0 :(得分:1)
只需定义一个方法:
void chkBox_CheckedChanged(object sender, EventArgs e)
{
var chkBox = sender as CheckBox;
if (chk.Checked == true)
{
lstOne.Items.Add(chkBox.Text);
}
else
{
lstOne.Items.Remove(chkBox.Text);
}
}
并附上所有CheckBox CheckedChanged
事件:
chckOne.CheckedChanged += chkBox_CheckedChanged;
chckTwo.CheckStateChanged += chkBox_CheckedChanged;
或者,如果您想在按钮中添加所有选中的值,请单击更改您的方法:
void btnOne_Click(object sender, EventArgs e)
{
this.Controls.OfType<CheckBox>()
.Where(c => c.Checked == true)
.Select(c => c.Text)
.ForEach(text => lstOne.Items.Add(text));
}
答案 1 :(得分:0)
List<CheckBox> cbList=new List<CheckBox>();
public Form1()
{
InitializeComponent();
btnOne.Click += btnOne_Click;
cbList.Add(chckOne);
cbList.Add(chckTwo);
//All the checkbox should be added into cbList.
}
void btnOne_Click(object sender, EventArgs e)
{
lstOne.Items.Clear();
var checked_checkbox = cbList.Where(cb=>cb.Checked==true).ToList();
if(checked_checkbox.Count>0)
{
checked_checkbox.ForEach(x=>lstOne.Items.Add(x.Text));// Maybe you want put text of checkbox into listbox.
}
}