【发布时间】:2020-06-30 11:19:09
【问题描述】:
我正在创建一个在线测试应用程序,其中我在运行时在表单加载时生成大约 100 个按钮。这是一段代码:
private void addQuestion_Reviewbutton()
{
for (int i = 1; i <= clsGlobalVars.gnTotalQuestion; i++)
{
Button button = new Button();
button.Location = new Point(160, 30 * i + 10);
button.Click += new EventHandler(ButtonClickOneEvent);
button.Tag = i;
button.Name = "Question" + i;
button.Text = i.ToString();
button.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.button));
button.BackgroundImageLayout = ImageLayout.Stretch;//.Zoom;
button.FlatAppearance.BorderSize = 0;
button.Size = new System.Drawing.Size(47, 41);
button.BackColor = Color.Transparent;
button.FlatStyle = FlatStyle.Flat;
button.Font = new System.Drawing.Font("Segoe UI Semibold", 12);
button.ForeColor = Color.White;
button.Cursor = Cursors.Hand;
flowLayoutPanel1.Controls.Add(button);
}
}
点击此按钮,我将更改背景颜色。
void ButtonClickOneEvent(object sender, EventArgs e)
{
Button button = sender as Button;
//button.BackColor = Color.Yellow;
button.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.button_Orange));
lblQuestionNo.Text = ((int)button.Tag).ToString()+".";
btnNext.Focus();
}
我在表单上有一个名为“下一步”的按钮。现在我的问题是,如果我目前的问题是“1”。然后我按下按钮我想更改文本为“2”的按钮的背景图像。
我需要您的宝贵指导来解决这个问题。
【问题讨论】:
-
你用什么技术创造这个?这是网络表单吗?
-
所以如果当前
Button有Tag == 1你想找到Button和Tag == 2?为什么不直接遍历这些按钮?还是借助 Linq 查询?var nextButton = flowLayoutPanel1.Controls.OfType<Button>().FirstOrDefault(btn => btn.Tag == currentButton.Tag + 1); -
您可以将下一个按钮标签作为CommandArgument 传递,以省去必须转换回
int以增加的麻烦。 -
您不应该在 2021 年将 WebForms 用于新项目。它已经过时了 13 年。 哎呀。
-
“我需要您的宝贵指导来解决这个问题。” - 我的指导是让您立即停止并在 ASP.NET Core 或至少 ASP.NET MVC(用于 .NET Framework)中重新开始,否则您将花费越来越多的时间不能很好地与现代网络浏览器配合使用的网络框架。例如,服务器上处理的每个“事件”都需要一个表单
POST,这会破坏用户浏览器的后退按钮,这是一个非常糟糕的用户体验(所以如果用户提交了十几个问题的答案(每个 需要他们自己的POST) 然后不小心导航回来他们已经失去了一切。