简体   繁体   English

动态地向表C#添加新行

[英]Add a new row dynamically to Table C#

Below is the code that creates a table and dynamically shows items from a database. 以下是创建表并动态显示数据库中项目的代码。 This work great, I would like to add a row on a onclick event from a button and make the data persistent when I click the button and not lose data. 这项工作很棒,我想在按钮的onclick事件上添加一行,并在单击按钮时使数据持久化而不丢失数据。 Any help would be appreciated. 任何帮助,将不胜感激。

Table tb = new Table();
tb.BorderWidth = 1;
tb.Width = new Unit("740px");
tb.BorderStyle = BorderStyle.Solid;
tb.ID = "myTable";

TableRow tr = new TableRow();
TableRow tr2 = new TableRow();
TableRow trEndRow = new TableRow();
foreach (QuestionBuilder QB in GetQuestionsDatabySection)
{
    TableCell tc1 = new TableCell();
    tc1.Text = OQB.QuestionText;
    tc1.BorderWidth = 1;
    tr.Cells.Add(tc1);
    tb.Rows.Add(tr);

    TableCell tc2 = new TableCell();
    tc2.Controls.Add(getControl(OQB.DynamicAttributeId, "0"));
    tc2.BorderWidth = 1;
    tr2.Cells.Add(tc2);
    tb.Rows.Add(tr2);

    TableCell tcEnd = new TableCell();
    Button btn = new Button();
    btn.Text = "Add Row";
    btn.Attributes.Add("OnClick", "ButtonAddRow_Click");
    btn.Attributes.Add("runat", "server");

    tcEnd.Controls.Add(btn);
    tcEnd.BorderWidth = 1;
    trEndRow.Cells.Add(tcEnd);
    tb.Rows.Add(trEndRow);
    // Add to PlaceHolder
    phTable.Controls.Add(tb);
}

Since you're doing a web app in ASP.NET you'll need to use something to manage your state. 由于您在ASP.NET中使用Web应用程序,因此需要使用某些方法来管理状态。 Here's a good breakdown from Microsoft on your options: https://msdn.microsoft.com/en-us/library/z1hkazw7.aspx 这是Microsoft提供的有关您选择的详细分类: https : //msdn.microsoft.com/zh-cn/library/z1hkazw7.aspx

Depending on the complexity of your data, view state and query strings are pretty common implementations, but that article highlights the advantages and disadvantages of each option. 根据数据的复杂性,视图状态和查询字符串是非常常见的实现,但是该文章重点介绍了每个选项的优缺点。 Once you've decided on which option you want to go with, it should be pretty easy to Google an example of how it's used. 一旦确定了要使用的选项,Google便会很容易地举例说明如何使用它。

Theoretically you could even reload the data from the database on each post back, if you were inclined to do so. 从理论上讲,如果您愿意,甚至可以从每个回发数据库中重新加载数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM