简体   繁体   中英

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. 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. Here's a good breakdown from Microsoft on your options: https://msdn.microsoft.com/en-us/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.

Theoretically you could even reload the data from the database on each post back, if you were inclined to do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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