Creating a Textbox dynamically in for loop

前端 未结 3 1436
别那么骄傲
别那么骄傲 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:54

    Replace this line

    dsmissing.Tables[0].Rows[tblCols- 1]["NewCompanyName"].ToString();
    

    With

    dsmissing.Tables[0].Rows[k]["NewCompanyName"].ToString();
    

    I assume you are talking about ID like below.

    for (int k = 0; k < tblCols; k++)
    {
        TableCell tc = new TableCell(); 
        TextBox txtCompanyName = new TextBox();
        txtCompanyName.Text = dsmissing.Tables[0].Rows[k]["NewCompanyName"].ToString();
        txtCompanyName.ID = Guid.NewGuid().ToString("N");
        tc.Controls.Add(txtCompanyName);
    }
    
    0 讨论(0)
  • 2021-01-28 07:55

    I think you may have meant to do this:

    for (int k = 0; k < tblCols; k++)
    {
        TableCell tc = new TableCell(); 
        TextBox txtCompanyName = new TextBox();
        //txtCompanyName.Text = dsmissing.Tables[0].Rows[tblCols-1 ["NewCompanyName"].ToString();
        txtCompanyName.Text = dsmissing.Tables[0].Rows[k]["NewCompanyName"].ToString();
        tc.Controls.Add(txtCompanyName);
    }
    
    0 讨论(0)
  • 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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题