在for循环中动态创建文本框

时间:2012-03-22 19:08:50

标签: asp.net

我试图动态创建一个表并在其中放置文本框。在下面的代码中,我试图为每个k创建一个具有不同名称的文本框。但只有k的最后一个值才会显示在文本框中。我想知道如何给Textbox命名,以便显示所有内容。

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();
tc.Controls.Add(txtCompanyName);
}

3 个答案:

答案 0 :(得分:0)

替换此行

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

使用

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

我假设您正在谈论ID如下。

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

答案 1 :(得分:0)

我想你可能有意这样做:

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

答案 2 :(得分:0)

肯定会有效,而且很容易理解

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