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

4

1 回答 1

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.

 }
于 2013-04-10T22:02:05.910 回答