2013-04-10 1 views
0

동적으로 많은 버튼이있는 테이블을 만듭니다. 목표는 버튼을 클릭 할 때마다 옆에있는 버튼이 색상을 변경한다는 것입니다. 그러나 버튼을 클릭 할 때마다 클릭 한 색상이 변경됩니다. 옆에있는 것은 두 번째 클릭 후에 만 ​​색이 바뀝니다.동적으로 생성 된 버튼은 두 번째 클릭까지 실행되지 않습니다.

나는 이것에 아주 새롭고 나의 영어는 그렇게 좋지 않으므로 가능한 한 평이한 설명을 할 수 있다면 그렇게하는 것이 가장 좋을 것입니다.

protected void Page_Load(object sender, EventArgs e) 
{ 
    Table tavla = new Table(); //New Table 
    tavla.GridLines = GridLines.Both; //Gridlines 
    tavla.BorderWidth = 4; //BorderWidth 
    tavla.ID = "tbl1"; //Table ID 
    Button btn = null; //New Button 
    for (int i = 1; i <= 8; i++) 
    { 
     TableRow myline = new TableRow(); 
     for (int j = 1; j <= 8; j++) 
     { 

      TableCell ta = new TableCell(); 
      ta.HorizontalAlign = HorizontalAlign.Center; 
      btn = new Button(); 
      btn.Width = 40; 
      btn.Height = 30; 
      btn.ID = i.ToString() + j.ToString(); 

      btn.Text = btn.ID.ToString(); 
      if ((btn.ID == "54") || (btn.ID == "45")) 
      { 
       btn.BackColor = Color.Black; 
       btn.Text = btn.ID.ToString(); 
       btn.ForeColor = Color.Aqua; 
      } 
      else if ((btn.ID == "44") || (btn.ID == "55")) 
      { 
       btn.BackColor = Color.Red; 
       btn.Text = btn.ID.ToString(); 
       btn.ForeColor = Color.Aqua; 
      } 

      else 
      { 
       btn.BackColor = Color.Empty; 
       btn.ForeColor = Color.Black; 
      } 
      btn.Click += new EventHandler(Checking); 
      ta.Controls.Add(btn); 
      myline.Cells.Add(ta); 

     } 

     tavla.Rows.Add(myline); 
    } 

    Panel1.Controls.Add(tavla); 

} 

protected void Checking(object sender, EventArgs e) 
{ 

    Button btn1 = sender as Button; // New button. 
    btn1.ID = (int.Parse(btn1.ID) + 1).ToString(); // Button ID += 1 
    btn1.BackColor = Color.Red; // Button changes color 
    this.Label1.Text = btn1.ID.ToString(); //Label showing the ID of button clicked. 

} 

최종 결과 :

여기 코드의 점검 방법에 http://i50.tinypic.com/260frb9.png

답변

0

, 당신은 잘못 방금 클릭 버튼의 ID를 수정하고 있습니다.

당신이 원하는 것은 (코드 실수가있을 수 있습니다 내 머리 위로의)이 같은 것입니다 :

내가 너무 생각 무엇
protected void Checking(object sender, EventArgs e) 
{ 
    Button btn1 = sender as Button; // New button. 
    string nextId = (int.Parse(btn1.ID) + 1).ToString(); 
    Button nextBtn = btn1.Parent.FindControl(nextId) as Button; 
    //check here to make sure nextBtn is not null :) 
    nextBtn.BackColor = Color.Red; // Button changes color 
    this.Label1.Text = btn1.ID.ToString(); //Label showing the ID of button clicked. 

} 
+0

. 하지만 두 번째 클릭 다음 버튼의 색상이 바뀌는 이유를 모르겠습니다. 클릭 한 버튼 만 색상을 변경해야합니다. –

+0

놀라운, 정말 고마워요! Peri의 목표는 실제로 다음 버튼의 색상을 지정하는 것이 아니라 다음 버튼의 색상을 지정하는 것입니다. 어쨌든 rivarolle, 당신은 나를 많이 도와 주셔서 감사합니다!. – user2268024

관련 문제