Creating a Textbox dynamically in for loop

前端 未结 3 1585
别那么骄傲
别那么骄傲 2021-01-28 07:19

I was trying to create a table dynamically and put textboxes in it. Here in the following code, i was trying to create a textbox with a distinct name for each k. But only the l

3条回答
  •  独厮守ぢ
    2021-01-28 07:59

    Surely this will work and it is easy to understand

    protected void Page_Load(object sender, EventArgs e)
    {
        button1();
    }
    protected void Page_Init(object sender, EventArgs e)
    {
        try
        {
            Label lbl = new Label();
            lbl.ID = "lbl_label";
            lbl.Text = "Enter the values";
            form1.Controls.Add(lbl);
            TextBox tb = new TextBox();
            tb.ID = "tbx_textbox";
            form1.Controls.Add(tb);
            Button bt = new Button();
            bt.ID = "bt_button";
            bt.Text = "click";
            form1.Controls.Add(bt);
    
        }
        catch (Exception ex) { }
    }
    public void button1()
    {
        Table table = new Table();
        TableRow row = null;
        TableCell cell = null;
        TextBox tbx1 = this.Page.FindControl("tbx_textbox") as TextBox;
        try
        {
            int a = int.Parse(tbx1.Text);
            for (int i = 0; i < a; i++)
            {
                row = new TableRow();
                cell = new TableCell();
                TextBox tx = new TextBox();
                tx.ID = "box" + i.ToString();
                cell.Controls.Add(tx);
                row.Cells.Add(cell);
                table.Rows.Add(row);
                form1.Controls.Add(table);
            }
            }
        catch (Exception ex) { }
        finally
        {
            table = null;
        }
    }
    

提交回复
热议问题