anairinac anairinac - 25 days ago 20
ASP.NET (C#) Question

ASP C#: How to get a table row from a control inside a cell

I have this table in my Page.aspx

<asp:Table ID="table1" runat="server" CssClass="tabla" ></asp:Table>


I am building dynamically
table1
in my Page.aspx.cs from a list using a foreach, adding 3 cells:

TableCell cell_name = new TableCell();
cell_name.Text = "Some name";
TableCell cell_active = new TableCell();
CheckBox checkbox = new CheckBox();
cell_active.Controls.Add(checkbox);
TableCell cell_actions = new TableCell();
ImageButton button = new ImageButton();
cell_actions.Controls.Add(button);

TableRow row = new TableRow();
row.Cells.Add(cell_name);
row.Cells.Add(cell_active);
row.Cells.Add(cell_actions);

table1.Rows.Add(row);


I want my ImageButton to have a onClick event and get from there the table row id (index inside the table) for the parent row of my ImageButton that was clicked. Is that possible? Any ideas?

Answer

Try this:

protected void Page_Load(object sender, EventArgs e)
{
        for (int i = 0; i < 3; i++)
        {
            TableCell cell_name = new TableCell();
            cell_name.Text = "Some name";

            TableCell cell_active = new TableCell();
            CheckBox checkbox = new CheckBox();
            cell_active.Controls.Add(checkbox);

            TableCell cell_actions = new TableCell();
            ImageButton button = new ImageButton();
            button.CommandArgument=i.ToString();
            button.Click += RowClick;
            cell_actions.Controls.Add(button);

            TableRow row = new TableRow();
            row.Cells.Add(cell_name);
            row.Cells.Add(cell_active);
            row.Cells.Add(cell_actions);

            table1.Rows.Add(row);
        }
}
protected void RowClick(object sender, EventArgs e)
{
        int rowIndex =int.Parse( ((ImageButton)sender).CommandArgument);
        Response.Write("RowIndex = " + rowIndex);
}