Reputation: 165
I have a table in my .aspx page as follows.
<table id="Test_Table">
</table>
I need to add a row dynamically in my .cs page for the above table:
I tried the following which I found.
I created a button on its onclick() I wrote the following code.
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
cell1.Text = "Sample Text";
row.Cells.Add(cell1);
Test_Table.Rows.Add(row);
But this is not working. It says that the table does not exist in the current context. Please Help.
Upvotes: 0
Views: 1297
Reputation: 460078
This is a html-table:
<table id="Test_Table">
You should add runat="server"
, then you can access it from serverside. But if you need to create rows dynamically you should use an ASP.NET Table
control in the first place.
<asp:Table runat="server" ID="Test_Table">
</asp:Table>
Now you can access it via Id
and Rows
-property.
// ...
Test_Table.Rows.Add(row);
However, note that it's not that simple to add controls dynamically in ASP.NET. They will be dosposed at the end of the page's current liefcycle, so as soon as the html was rendered and sent to the client. You need to recreate it on every postback in Page_Load
(at the latest) with the same ID (if any) as before.
Therefore you need to persist how many rows you have already added, you could use a ViewState
or Session
variable.
Upvotes: 1