Search code examples
c#asp.nethtml-tablerow

Name 'of table' does not exist in the current context


I've this table with rows and now I'm working on a button that dynamically adds a row. I think I've the right code but my Visual Studio gives an error that says 'The name 'kost_tbl' does not exist in the current context.'

This is my frontend table:

<table id="kost_tbl" runat="server" border="1" width="100%">
                <tr>
                    <td width="12%" height="30px">1</td>
                    <td width="22%">2</td>
                    <td width="22%">3</td>
                    <td width="22%">4</td>
                    <td>Totaal</td>
                </tr>
                <tr>
                    <td height="25px" style="background-color:#ddd;">1.1 </td>
                    <td>1.2</td>
                    <td>1.3</td>
                    <td>1.4</td>
                    <td>1.5</td>
                </tr>

The function that ads a row is written like this:

protected void btnAddCost_Click(object sender, EventArgs e)
{

int totalRows = 1;
int totalColumns = 5;

for (int r = 0; r <= totalRows; r++)
{
    System.Web.UI.HtmlControls.HtmlTableRow tableRow = new HtmlTableRow();
    for (int c = 0; c <= totalColumns; c++)
    {
        System.Web.UI.HtmlControls.HtmlTableCell cell = new HtmlTableCell();
        TextBox txtBox = new TextBox();
        txtBox.Text = "Row: " + r + ", Col:" + c;
        cell.Controls.Add(txtBox);
        //Add the cell to the current row.
        tableRow.Cells.Add(cell);

        if (c == 5)
        {
            kost_tbl.Rows.Add(tableRow);
        }
    }
}
}

The error is about the last line of code, that's where he fails and says it doesn't exist though it has the same id and an runat="server".

Any ideas on what might be the problem? (I'm working with C# in ASP.net)


Solution

  • change this line:

    kost_tbl.Rows.Add(tableRow);
    

    To:

    Table kost_tbl = Page.FindControl("kost_tbl") as Table; 
    kost_tbl.Rows.Add(tableRow);