Click here to Skip to main content
15,892,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a table which i am dynamically generating based on user input. I am trying to insert a label text into table cell on button click. onclick of button a label text of a demo method should be inserted into table cells using javascript/ajax. Can someone suggest me how can i do this?

What I have tried:

JavaScript
<pre>function CreateTable(){
    var rowCtr;
    var cellCtr;
    var rowCnt;
    var cellCnt;

    var myTableDiv = document.getElementById('myDynamicTable');

    var table = document.createElement('table');
    table.setAttribute("contenteditable", "true");
    table.border = "1";
    table.id = "myTable";


    var tableBody = document.createElement('tbody');
    table.appendChild(tableBody);

    rowCnt = document.getElementById('txtrows').value;
    cellCnt = document.getElementById('txtcols').value;

    for (rowCtr = 0; rowCtr < rowCnt; rowCtr++) {

        var tr = document.createElement('tr');
        tableBody.appendChild(tr);

        for (cellCtr = 0; cellCtr < cellCnt; cellCtr++) {

            var td = document.createElement('td');
            td.width = '120';
            td.appendChild(document.createTextNode("Row:" + rowCtr + " Column:" + cellCtr));
            tr.appendChild(td);
        }
    }
    myTableDiv.appendChild(table);
  }

asp button:
<asp:Button ID="button1" Text="button" runat="server" OnClick="demo" />


C# Code:

public void demo()
{
    TableCell tcell = new TableCell();
    RadLabel rlbl = new RadLabel();
    rlbl.Text = "test";
    tcell.Controls.Add(rlbl);

}

protected void demo(object sender, EventArgs e)
{
    demo();
}
Posted
Updated 15-Oct-18 5:39am

1 solution

You are dynamically creating your HTML table at the client (JavaScript) and you are trying to insert a Label control on a TableCell which won't work because:

(1) Your C# code doesn't know the generated HTML Table you created - they are created on the client and there's a disconnected space between them.
(2) Your dynamic HTML will be lost on each postbacks as your server doesn't know the state your dynamic controls


You shouldn't mix your JavaScript implementation with your C# code behind logic. If you are generating your Table using JavaScript, then use JavaScript to insert a label element.
 
Share this answer
 
Comments
Syf AK 16-Oct-18 0:32am    
Thanks @Vincent. can i insert label control text at specific index using java script??
Vincent Maverick Durano 16-Oct-18 9:52am    
You can surely can. Label control will render as <span> element in the browser. So you an use the innerHTML attribute of the table cell and insert your span. For example:

table.rows[0].cells[0].innerHTML = '<span>' + 'Test' + '</span>';

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900