我正在动态创建一个包含许多按钮的表。目标是每次单击按钮时,它旁边的按钮都会改变其颜色。但是,每次单击按钮时,我单击的按钮都会更改其颜色。旁边的那个将仅在第二次点击后改变其颜色。
我对此非常陌生,而且我的英语不太好,所以如果你能尽可能简单地解释,那就最好了。
以下是代码:
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.
}
答案 0 :(得分: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.
}