You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过C#后端代码动态创建TextBox并操作后续生成的字段(保持表格结构)

How to Dynamically Add TextBox Rows in ASP.NET Using C# (Server-Side)

Hey there! I get that you're trying to add new rows of TextBoxes to your existing table using C# (no JavaScript allowed) while keeping the same structure, and you've hit a roadblock. Let's fix that together.

First, the key thing to remember with ASP.NET server-side dynamic controls is that they don't persist across postbacks on their own—you need to recreate them during the page lifecycle to keep them (and their values) around. Here's a step-by-step solution that matches your existing table structure:

Step 1: Update Your Code-Behind (C#)

Add this code to your page's code-behind file. It handles creating new rows and recreating them after postbacks:

protected void Page_Load(object sender, EventArgs e)
{
    // Recreate dynamically added rows every time the page loads
    // This ensures they don't disappear after postbacks
    RecreateDynamicRows();
}

protected void btnCreate_Click(object sender, EventArgs e)
{
    // Create a new table row matching your original structure
    TableRow newRow = new TableRow();

    // Add 4 TextBox cells (same as the original row)
    for (int i = 1; i <= 4; i++)
    {
        TableCell textBoxCell = new TableCell();
        TextBox newTextBox = new TextBox();
        
        // Give each TextBox a unique ID (critical for state tracking)
        newTextBox.ID = $"txtDynamic_{Guid.NewGuid()}_{i}";
        // If you have a CSS class for your TextBoxes, add it here to match styles:
        // newTextBox.CssClass = "your-textbox-class";
        
        textBoxCell.Controls.Add(newTextBox);
        newRow.Cells.Add(textBoxCell);
    }

    // Add the final empty cell (matches the original row's last cell with the Create button)
    TableCell emptyCell = new TableCell();
    newRow.Cells.Add(emptyCell);

    // Add the new row to your table
    tbform.Rows.Add(newRow);

    // Save the number of dynamic rows to ViewState so we can recreate them later
    int dynamicRowCount = ViewState["DynamicRowCount"] != null ? (int)ViewState["DynamicRowCount"] : 0;
    ViewState["DynamicRowCount"] = dynamicRowCount + 1;
}

private void RecreateDynamicRows()
{
    if (ViewState["DynamicRowCount"] == null) return;

    int rowCount = (int)ViewState["DynamicRowCount"];
    for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
    {
        TableRow newRow = new TableRow();

        for (int i = 1; i <= 4; i++)
        {
            TableCell textBoxCell = new TableCell();
            TextBox newTextBox = new TextBox();
            // We use a consistent ID pattern to ensure state is restored correctly
            newTextBox.ID = $"txtDynamic_{Guid.NewGuid()}_{i}";
            // Don't forget to apply your CSS class here too if needed
            
            textBoxCell.Controls.Add(newTextBox);
            newRow.Cells.Add(textBoxCell);
        }

        TableCell emptyCell = new TableCell();
        newRow.Cells.Add(emptyCell);

        tbform.Rows.Add(newRow);
    }
}

Key Notes to Make This Work:

  • ViewState for Persistence: We store the number of dynamic rows in ViewState so we know how many to recreate on each postback. Without this, your new rows would disappear as soon as the page refreshes.
  • Unique IDs: Every dynamic TextBox needs a unique ID. Using Guid.NewGuid() ensures no duplicates, which is essential for ASP.NET to track the control's state (like user input) across postbacks.
  • Matching Structure: We're creating exactly 4 TextBox cells plus one empty cell, just like your original row—this keeps your table's styling consistent.

Bonus: How to Get Values from Dynamic TextBoxes

If you need to retrieve the text entered into these dynamic TextBoxes (e.g., on a submit button click), you can loop through the table's rows and cells:

protected void btnSubmit_Click(object sender, EventArgs e)
{
    foreach (TableRow row in tbform.Rows)
    {
        foreach (TableCell cell in row.Cells)
        {
            foreach (Control control in cell.Controls)
            {
                if (control is TextBox textBox)
                {
                    string userInput = textBox.Text;
                    // Do something with the input (save to database, validate, etc.)
                }
            }
        }
    }
}

Just add a submit button to your page's table (either in the original row or a new one) and hook it up to this event.

内容的提问来源于stack exchange,提问作者Joshua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 14:52:36