我创建了一个Windows窗体应用程序,该窗体在加载form1时在其中添加了一些按钮。我想在单击form2按钮时更改form1按钮的颜色
Point newLoc = new Point(20, 35);
int ButtonHeight = 0;
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 1; i < 20; i++)
{
Button b = new Button
{
Name = "Btn" + i.ToString(),
Size = new Size(120, 60),
Location = newLoc, Text = i.ToString(),
BackColor = System.Drawing.Color.PaleGreen
};
i++;
if ((i % 10) == 0)
{
ButtonHeight = ButtonHeight + b.Height + 10;
newLoc = new Point(-110, 25 + ButtonHeight);
}
newLoc.Offset(b.Width + 10, 0);
Controls.Add(b);
}
}
public void Changecolor(Button b)
{
b.BackColor = System.Drawing.Color.Yellow;
}
private void Form1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
}
//form2
private void button1_Click(object sender, EventArgs e)
{
Button b = new Button
{
Name = "Btn" + textBox1.Text
};
Form1 f1 = new Form1();
f1.Change_color(b);
}
如果我在form2.textbox中键入数字,然后单击form2.button。它应使用名称“ Btn” + textBox1.Text更改form1.button的背景色
答案 0 :(得分:0)
button.BackColor = Color.Red
您希望它发生的任何地方
答案 1 :(得分:0)
使用new关键字调用其他函数时,通常无法更改其属性。 您需要为开瓶器表单声明一个对象,并将其设置为如下所示的组件(请更改您的名字,它将为您工作):
//In form 2:
var frmName= (frmName)Application.OpenForms["frmName"];
frmName.Button1.BackColor=Color.Red
编辑:是的,您可以访问动态创建的按钮,但需要将访问修饰符更改为public。
// In form1:
public Button b =new Button();
private void button8_Click(object sender, EventArgs e)
{
b.Name = "btn";
b.Size = new Size(120, 60);
b.Text = "denemee";
b.BackColor = System.Drawing.Color.PaleGreen;
Controls.Add(b);
}