我的 Page.aspx 中有这个表
<asp:Table ID="table1" runat="server" CssClass="tabla" ></asp:Table>
我在我的 Page.aspx.cs 中使用 foreach 从列表动态构建 table1
,添加 3 个单元格:
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);
我希望我的 ImageButton 有一个 onClick 事件,并从那里获取被单击的我的 ImageButton 父行的表行 ID(表内索引)。那可能吗?有什么想法吗?
最佳答案
试试这个:
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);
}
关于c# - 如何从单元格内的控件获取表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21200212/