2014-03-06 77 views
0

我有一个固定的ImageButton和一些ImageButtons在Page_Load动态添加的表。在页面“查看源”他们看起来(比ID之外)相同:动态添加imagebuttons不添加到page.Request.Form

<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。

我知道所有ImageButton都会发生回传,因为我更新(在Page_Load中)带有ID的标签(用于测试目的) - 对于所有动态ImageButton都是空白的,对于固定的是“ibSel_020”的ImageButton。

我该如何判断哪个动态添加的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); 
} 

希望它能帮助。

UPDATE:

为了测试,我写的代码块堆积在字符串中的所有元素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被重新创建的代码之前有'Magic Code'的时候。

BOTTOM LINE:您不能Page.FindControl(zDynamicControl)直到它被重新创建。

+0

你是如何生成和添加这些按钮? – Andrei

+0

将代码添加到您创建按钮的位置 – Plue

+0

@Murali - 呃,呈现的HTML位于我的原始文章中。 –

回答

0

试试这个。

Dynamically bind eventhandler at runtime

这会帮助你得到这会导致回发的控件的ID。

在你的EventHandler中,你可以像这样得到你的控件的ID。

void imgBtn_Click(object sender, ImageClickEventArgs e) 
{ 
    //((ImageButton)sender).ID 
} 
+0

感谢您的回复RKS。表(实际上是asp:Table)已经存在,就像存在固定ImageButton的一个asp:TableRow一样。动态ImageButton被添加到新asp:TableRow的asp:Table中。 –

+0

我实际上是先编码你的解决方案,但由于鸡蛋问题不得不放弃它。直到Page_Load之后才会发生EH。但是这太迟了,因为在这个渲染中要添加哪个动态ImageButtons取决于点击之前渲染的哪个动态ImageButton。我希望我很清楚,谢谢你的建议。 –