【发布时间】:2014-03-06 14:33:28
【问题描述】:
我有一个带有固定 ImageButton 的表和一些在 Page_Load 中动态添加的 ImageButton。在“查看源代码”页面中,它们看起来相同(除了 ID):
<tr>
<td>
<input type="image" name="ctl00$cphMain$ibSel_020" id="cphMain_ibSel_020" src="/Images/Deselected.gif" />
</td>
<td>Fixed ImageButton
</td>
</tr>
<tr>
<td>
<input type="image" name="ctl00$cphMain$ibSel_001" id="cphMain_ibSel_001" src="/Images/Deselected.gif" />
</td>
<td>Dynamic ImageButton
</td>
</tr>
....plus ten more dynamically added ImageButtons ibSel_002 through ibSel_011.
在 Page_Load 事件中,我通过遍历 page.Request.Form 来确定哪个控件导致回发。如果我单击固定的 ImageButton,如果在 page.Request.Form 中找到为“ibSel_020”。如果我单击任何动态 ImageButton,则找不到 ID。
我知道所有 ImageButtons 都会发生回发,因为我让它更新(在 Page_Load 中)带有 ID 的标签(用于测试目的)——对于所有动态 ImageButtons 和固定 ImageButton 的“ibSel_020”是空白的.
如何判断是哪个动态添加的 ImageButton 导致了回发?
下面是一些生成 ImageButtons 的代码:
for(int Q = 0; Q < g_zTypes.GetLength(0); Q++){
TableRow tr = new TableRow();
TableCell tc = new TableCell(); //Add image button to row
ImageButton ib = new ImageButton();
ib.ID = "ibSel_" + Q.ToString().PadLeft(3, '0');
ib.ImageUrl = "/Images/Deselected.gif";
tc.Controls.Add(ib);
tr.Cells.Add(tc);
tc = new TableCell(); //Add extra cell to row
tc.Text = g_zTypes[Q, 1];
tr.Cells.Add(tc);
tblType.Rows.Add(tr);
}
希望对你有帮助。
更新:
为了测试,我编写了一段代码来将所有 page.Request.Form 元素累积在一个字符串中。在 Page_Load 结束时,我是 Response.Writing zMagic。这是块:
//=============MAGIC CODE=========================
Control cF;
string zF;
foreach(string zControl in Page.Request.Form){
//For ImageButtons crop off mouse coordinates property
if(zControl.EndsWith(".x") || zControl.EndsWith(".y")){
cF = Page.FindControl(zControl.Substring(0, zControl.Length - 2));
}
else{
cF = Page.FindControl(zControl);
}
zF = (cF == null) ? "NULL" : cF.ToString();
zMagic += "<br />Form[" + zControl + "]=[" + zF + "]<br />";
}
zMagic += "[END]";
//================================================
我发现动态添加的 ImageButtons 实际上存在,无论我在 Page_Load 中的哪个位置粘贴了“魔术代码”。发生的事情是 Page.FindControl() 失败了——但前提是我在重新创建动态 ImageButton 的代码之前有“魔术代码”。
底线:在重新创建 Page.FindControl(zDynamicControl) 之前,您无法使用它。
【问题讨论】:
-
你是如何生成和添加这些按钮的?
-
添加创建按钮的代码
-
@Murali - 嗯,渲染的 HTML 在我的原始帖子中。
-
您是否尝试过 string senderPostBack = Request["__EVENTTARGET"];?