在asp.net中动态生成Button

时间:2016-05-18 18:10:02

标签: c# asp.net asp.net-mvc

我在asp.net网络表单中获得了一项任务,以15分钟的步长(ButtonsLabels动态生成10:00 / 10:15时间间隔值,10: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";
    }
}

3 个答案:

答案 0 :(得分:2)

 void CreateControl()
    {
        TimeSpan FifteenMinutes = new TimeSpan(0, 15, 0);
        TimeSpan Time = new TimeSpan(0,0,0);
        int i = 1;
        while (Time.Hours != 24)
        {
            Button btn1 = new Button();
            btn1.ID = "btn"+i;
            btn1.CommandArgument = i.ToString();
            btn1.Text = "click me";
            btn1.Click += new EventHandler(btn1_Click);
            div1.Controls.Add(btn1);

            Label lbl = new Label();
            lbl.Text = Time.ToString();
            div1.Controls.Add(lbl);

            Time = Time.Add(FifteenMinutes);

            i++;
        }
    }

答案 1 :(得分:2)

您可以使用TimeSpan并在每次迭代时将时间增加15分钟。

int j = 0;
for (TimeSpan i = new TimeSpan(10, 0, 0); i.ToString(@"hh\:mm") != "12:00"; i = i.Add(new TimeSpan(0, 15, 0)), j++)
{
    Button btn1 = new Button();
    btn1.ID = "btn" + j;
    btn1.Text = i.ToString(@"hh\:mm");
    btn1.Click += new EventHandler(btn1_Click);
    div1.Controls.Add(btn1);

    Label lbl = new Label();
    lbl.Text = i.ToString(@"hh\:mm");
    div1.Controls.Add(lbl);

    Console.WriteLine(i.ToString(@"hh\:mm"));
}

void btn1_Click(object sender, EventArgs e)
{
    string buttonId = ((Button)sender).ID;
    div1.InnerHtml += "Button: " + buttonId + " was clicked";
}

答案 2 :(得分:2)

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";
    }
}