我最多有10个文本框,我希望他们在用户的输入上更改BackColor。
目前我使用当前代码:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "1")
{
textBox2.BackColor = Color.DarkRed;
textBox2.Visible = true;
textBox3.Visible = false;
textBox4.Visible = false;
textBox5.Visible = false;
textBox6.Visible = false;
textBox7.Visible = false;
textBox8.Visible = false;
}
else if (textBox1.Text == "2")
{.......
但是为10个(或更多)盒子制作这个盒子花费的时间太长了。
答案 0 :(得分:2)
首先将需要更改颜色/可见度的所有文本框添加到面板中。
一旦完成,您可以使用以下
int counter;
if(!int.TryParse(textBox1.Text, out counter))
return;
int currentCounter = 0;
foreach(var tb in panelName.Controls.OfType<TextBox>())
{
if(currentCounter++ < counter)
{
tb.BackColor = Color.DarkRed;
tb.Visible = true;
}
else
{
tb.Visible = false;
}
}
答案 1 :(得分:0)
您可以使用以下方法:
Control[] controls = { textBox2, textBox3, textBox4, textBox5, textBox6, textBox7, textBox8 };
int controlNum;
if(int.TryParse(textBox1.Text.Trim(), out controlNum)
&& controlNum > 0 && controlNum <= controls.Length)
{
Control activeControl = controls[controlNum - 1];
activeControl.BackColor = Color.DarkRed;
activeControl.Visible = true;
foreach(Control unactiveControl in controls.Where(c => c != activeControl))
unactiveControl.Visible = false;
}
如果您想要对用户指定的控件数量应用更改:
int controlCount;
if (int.TryParse(textBox1.Text.Trim(), out controlCount)
&& controlCount > 0 && controlCount <= controls.Length)
{
var activeControls = controls.Take(controlCount);
var unactiveControls = controls.Skip(controlCount);
foreach (Control activeControl in activeControls)
{
activeControl.BackColor = Color.DarkRed;
activeControl.Visible = true;
}
foreach (Control unactiveControl in unactiveControls)
{
unactiveControl.BackColor = Color.Black;
unactiveControl.Visible = false;
}
}
答案 2 :(得分:0)
减少您要编写的代码量的一种方法是将其打开。而不是思考如果textbox1是&#34; 1&#34;然后设置textbox2可见&#39;,想一想textbox2何时可见?&#39;
作为一个例子,并基于您所展示的有限逻辑:
textbox2.Visible = textbox1.Text == "1";
这会在true
时设为1
,否则为false
。