
老师给我们布置了一个作业。复选框是学生可以选择的课程,它们下面的标签是免费的。基本上,每次选课(复选框)时,在标签处连接到它的数字应该减少。如果有人不检查它,数字应该返回basic。
对不起,我的英语,我希望这是可以理解的。
发布于 2020-09-11 01:22:05
您可以尝试为每个复选框订阅CheckedChanged事件。并使用Convert.ToInt32法获取标签中的值。然后判断通过swicth statement选择的复选框。
public Form1()
{
InitializeComponent();
checkBox1.CheckedChanged += checkBox_CheckedChanged;
checkBox2.CheckedChanged += checkBox_CheckedChanged;
checkBox3.CheckedChanged += checkBox_CheckedChanged;
}
private void checkBox_CheckedChanged(object sender, EventArgs e)
{
if (((CheckBox)sender).Checked)
{
switch (((CheckBox)sender).Name)
{
case "checkBox1":
labelofcb1.Text = (Convert.ToInt32(labelofcb1.Text) + 1).ToString();
break;
case "checkBox2":
labelofcb2.Text = (Convert.ToInt32(labelofcb2.Text) + 1).ToString();
break;
case "checkBox3":
labelofcb3.Text = (Convert.ToInt32(labelofcb3.Text) + 1).ToString();
break;
}
}
else
{
switch (((CheckBox)sender).Name)
{
case "checkBox1":
labelofcb1.Text = (Convert.ToInt32(labelofcb1.Text) - 1).ToString();
break;
case "checkBox2":
labelofcb2.Text = (Convert.ToInt32(labelofcb2.Text) - 1).ToString();
break;
case "checkBox3":
labelofcb3.Text = (Convert.ToInt32(labelofcb3.Text) - 1).ToString();
break;
}
}
}发布于 2020-09-11 01:12:13
在这个例子中,我选择了每个checkboxs的checkboxs属性,这是每个checkboxs中的函数。您可以通过更改0、++或--来更改初始值或更改的值。您只需将两个if条件从每个函数添加到函数中,并更改其中的名称以反映标签的名称。
public partial class Form1 : Form
{
int counter=0;
public Form1()
{
InitializeComponent();
label1.Text = counter.ToString();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
counter++;
label1.Text = counter.ToString();
}
if (!checkBox1.Checked)
{
counter--;
label1.Text = counter.ToString();
}
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
if (checkBox3.Checked)
{
counter++;
label1.Text = counter.ToString();
}
if (!checkBox3.Checked)
{
counter--;
label1.Text = counter.ToString();
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked)
{
counter++;
label1.Text = counter.ToString();
}
if (!checkBox2.Checked)
{
counter--;
label1.Text = counter.ToString();
}
}
}https://stackoverflow.com/questions/63838911
复制相似问题