gpt4 book ai didi

c# - asp.net中动态生成Button

转载 作者:太空宇宙 更新时间:2023-11-03 19:00:14 25 4
gpt4 key购买 nike

我在 asp.net web 表单中获得了一项任务,以动态生成 Buttons/Labels 的时间间隔为 15 分钟(10: 0010:1510:30 ... 12:00)通过使用循环。

public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

protected void Timer1_Tick(object sender, EventArgs e)
{
CreateControl();
}

void CreateControl()
{
Button btn1 = new Button();
btn1.ID = "btn1";
btn1.Text = "click me";
btn1.Click += new EventHandler(btn1_Click);
div1.Controls.Add(btn1);
}

void btn1_Click(object sender, EventArgs e)
{
div1.InnerHtml += "btn1 was clicked";
}
}

最佳答案

public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TimeSpan startTime = new TimeSpan(0, 0, 0);
TimeSpan endTime = new TimeSpan(1, 0, 0);
int i = 0;

While(startTime <= endTime)
{
i++;
CreateControl(startTime.ToString(@"hh\:mm\:ss"), i);
startTime += TimeSpan.FromMinutes(15); //Add 15 minutes
}
}


void CreateControl(string printTime, increment)
{
Button btn1 = new Button();
btn1.ID = "btn_" + increment;
btn1.Text = printTime;
btn1.Click += new EventHandler(btn_Click);
div1.Controls.Add(btn1);
}

void btn_Click(object sender, EventArgs e)
{
string ID = (sender as Button).ID;
div1.InnerHtml += "btn " + ID + " was clicked";
}
}

关于c# - asp.net中动态生成Button,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37307189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com