way to put linkbutton into tablecell, asp.net

Viewed 58

Here is the part of a code which builds DB from SQL query, but I need to put extra cell for LinkButton.

for (int j = 0; j < numrows; j++)
{
    TableRow row = new TableRow();

    for (int i = 0; i < numcols; i++)
    {
        TableCell cell = new TableCell();
        string textContent;

        textContent = subjects.Rows[j][i].ToString();
        cell.Text = textContent;

        row.Cells.Add(cell);
    }

    TableCell cell1 = new TableCell();

    LinkButton button = new LinkButton();
    button.Text = "look";
    button.Click += new EventHandler(submit_Click2);

    cell1. = button;
    row.Cells.Add(cell1);
    table.Rows.Add(row);
}

The question is that I don't know what do to with this part of a code where I put button into cell, I couldn't find a way to do it. Is it possible to do it without GridView, because I can't use it?

TableCell cell1 = new TableCell();

LinkButton button = new LinkButton();
button.Text = "look";
button.Click += new EventHandler(submit_Click2);

cell1. = button;
1 Answers

Here you go, a simple example. But remember to not add the table to the page within IsPostBack

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        //do not add dynamic controls like the linkbutton in the table in  "IsPostBack"
    }

    //to generate some random data
    var random = new Random();

    //number of rows and cells
    var rowCount = random.Next(5, 25);
    var cellCount = random.Next(3, 10);

    //create a new table
    var table = new Table()
    {
        CssClass = "table table-striped"
    };

    //add the rows
    for (int i = 0; i < rowCount; i++)
    {
        var row = new TableRow();

        //add the cells
        for (int j = 0; j < cellCount; j++)
        {
            //create a new cell
            var cell = new TableCell();

            //if the cell is not the last add content, otherwise add the linkbutton
            if (j < cellCount - 1)
            {
                cell.Text = "CellValue " + random.Next(1000, 100000).ToString();
            }
            else
            {
                //create a new linkbutton
                var lb = new LinkButton()
                {
                    Text = "LinkButton"
                };

                //add the click event handler
                lb.Click += new EventHandler(LinkButton_Click);

                //add the linkbutton to the cell
                cell.Controls.Add(lb);
            }

            //add the cell to the row
            row.Cells.Add(cell);
        }

        //add the row to the table
        table.Rows.Add(row);
    }

    //add the table to the page
    PlaceHolder1.Controls.Add(table);
}
Related