【问题标题】:how to add textboxes dynamically to a table row in C#如何在 C# 中将文本框动态添加到表格行
【发布时间】:2013-04-23 10:54:00
【问题描述】:

我想在 C# 中动态添加文本框,点击表格行中的按钮。为此,我使用了以下代码。 [1]:http://pastie.org/7702237.

问题是我可以根据需要添加任意数量的文本框,但它们在同一位置添加,我的意思是表格行不会因每次按钮单击而增加,而是只是用新的表格行替换旧表格行.请帮我解决这个问题。

提前致谢 象头神

【问题讨论】:

    标签: c# textbox dynamically-generated


    【解决方案1】:

    基于 Web 的应用程序不维护状态;为此,表的状态和任何变量都没有被维护。每次回发(由按钮生成)时,表的状态都会恢复到添加行之前的状态,然后以编程方式向其中添加一行。

    为了实现您的目标,您需要以某种方式维护状态。在以下代码 sn-p 中,我正在使用会话:

    private List<TableRow> TableRows
    {
        get
        {
            if(Session["TableRows"] == null)
                Session["TableRows"] = new List<TableRow>();
            return (List<TableRow>)Session["TableRows"];
        }
    }
    

    以下是修改后的代码以使用会话变量:

    TextBox txtE, txtM, txtB;
    Button btnAdd, btnDel;
    
    TableRow trow;
    TableCell tcell;
    
    foreach(TableRow tr in TableRows)
        tblEduDetails.Controls.Add(tr);
    
    int count = TableRows.Count + 1;
    
    txtE = new TextBox();
    txtE.ID = "E" + count.ToString();
    txtE.Visible = true;
    txtE.Text = "E " + count.ToString();
    txtE.BorderWidth = 2;
    txtE.TextMode = TextBoxMode.SingleLine;
    txtE.Height = 30;
    
    txtM = new TextBox();
    txtM.ID = "M" + count.ToString();
    txtM.Visible = true;
    txtM.Text = "M " + count.ToString();
    txtM.TextMode = TextBoxMode.SingleLine;
    txtM.Height = 30;
    
    txtB = new TextBox();
    txtB.ID = "E" + count.ToString();
    txtB.Visible = true;
    txtB.Text = "B " + count.ToString();
    txtB.TextMode = TextBoxMode.SingleLine;
    txtB.Height = 30;
    
    btnAdd = new Button();
    btnAdd.ID = "A" + count.ToString();
    
    btnDel = new Button();
    btnDel.ID = "D" + count.ToString();
    
    trow = new TableRow();
    trow.ID = "R" + count.ToString();
    trow.BorderWidth = 1;
    
    tcell = new TableCell();
    tcell.ID = "E" + count.ToString();
    tcell.Controls.Add(txtE);
    trow.Controls.Add(tcell);
    
    tcell = new TableCell();
    tcell.ID = "B" + count.ToString();
    tcell.Controls.Add(txtM);
    trow.Controls.Add(tcell);
    
    tcell = new TableCell();
    tcell.ID = "M" + count.ToString();
    tcell.Controls.Add(txtB);
    trow.Controls.Add(tcell);
    
    tblEduDetails.Controls.Add(trow);
    TableRows.Add(trow);
    

    【讨论】:

    • 这给出了错误,因为 TableRow 没有序列化,可以为它做什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 2020-09-22
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多