2014-11-26 1 views
0

저는 C# 프로그래밍의 완전한 멍청한 행동입니다. 이것은 내 문제입니다 : 버튼 1을 클릭하면 생성되는 패널이있는 양식이 있으며 패널에는 패널의 배경색을 변경하는 버튼 (btnColor1)도 있습니다. btnColor1에서 패널의 배경색을 참조하고 싶습니다만, "이름 'btnColor1'이 현재 컨텍스트에 존재하지 않습니다."라는 오류 메시지가 나타납니다. 이 문제를 어떻게 해결할 수 있습니까?C# 런타임에서 생성 된 버튼을 사용하여 패널의 속성 편집

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace TEST_APP_1 
{ 
public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 

     Panel myPanel1 = new Panel(); 
     myPanel1.Location = new System.Drawing.Point(100, 50); 
     myPanel1.Name = "Panel 1"; 
     myPanel1.Size = new System.Drawing.Size(200, 100); 
     myPanel1.BackColor = Color.Red; 

     TextBox textBox1 = new TextBox(); 
     textBox1.Location = new Point(10, 50); 
     textBox1.Text = "empty field"; 
     textBox1.Size = new Size(150, 30); 

     Button btnColor1 = new Button(); 
     btnColor1.Location = new Point(10, 10); 
     btnColor1.Text = "GOLD"; 
     btnColor1.Size = new Size(100, 30); 
     btnColor1.Click += myButton1_Click; 

     myPanel1.Controls.Add(textBox1); 
     myPanel1.Controls.Add(btnColor1); 

     Controls.Add(myPanel1); 
    } 

    private void myButton1_Click(object sender, EventArgs e) 
    { 
     throw new NotImplementedException(); 
     btnColor1.BackColor = Color.Gold; 
    } 
} 

}

+0

당신이 새로운 버튼, 새로운 패널을 필요로 확신을 모든 버튼을 클릭 할 때마다 생성됩니까? 그렇지 않다면 클래스에 필드로'btnColor1'을 저장하면됩니다. –

답변

0

당신은 패널과 양식에 액세스 버튼의 부모 속성을 사용하려고 할 수 있습니다

private void myButton1_Click(object sender, EventArgs e) 
    { 
     Button but = (sender as Button); 
     but.BackColor = Color.Gold; 
     // this changes the color of the panel 
     but.Parent.BackColor = Color.Gold; 
     // this changes the color of the form containing the panel 
     if (but.Parent.Parent != null) 
     { 
      but.Parent.Parent.BackColor = Color.Gold; 
     } 

    } 
2

btnColor1 그래서 이벤트 핸들러에서 참조하는 변수로서 존재하지 않는 경우를 Button1_Click 방법의 범위 내에서 선언된다. 여기에 이벤트 핸들러를 변경합니다

private void myButton1_Click(object sender, EventArgs e) 
    { 
     throw new NotImplementedException(); 
     (sender as Button).BackColor = Color.Gold; 
    } 
+0

감사합니다. Kell, 코드를 사용해 보았지만 휴식이있었습니다. 'throw new NotImplementedException();'를 삭제했지만,이 코드는 패널의 배경이 아니라 내 버튼을 금으로 만든다. 내 목표는 컨테이너의 색상을 변경하는 것뿐만 아니라 하나의 (런타임 생성 된) 버튼을 클릭하여 다른 컨트롤의 많은 다른 속성을 변경하는 것입니다. –

+0

@ Dr.Mojo, 필요한 경우, 그게 바로 당신이해야 할 일입니다. 이벤트 처리기로 수정하려는 각 속성에 대한 코드를 추가하고 수정 가능한 모든 컨트롤을 어떻게 든 액세스 가능하게 만듭니다. 현재 폼을 [열거 컨트롤] (http://stackoverflow.com/q/5265903/1997232) 할 수 있으며, 식별이나 다른 종류의 데이터를 저장하기 위해'Tag' 속성을 사용할 수 있습니다. 이 경우 모든 컨트롤 (예 :'btnColor1')의 현지화를 해제 (로컬이 아닌) 할 필요가 없습니다. – Sinatr

+0

예, Sinatr의 말 : – Kell

관련 문제