WebControls中的Button控制項或ImageButton在Render成 Html 後 type屬性會變成 submit 例:<input type="submit" value="submit">

這時在後端Page_Load中無法用Request.Form["__EVENTTARGET"]取得控制項ID,因為他們並不會觸發__doPostBack的機制

以下為替代方法

VB.Net 語法

Public Shared Function GetPostBackControl(page As Page) As Control                
    Dim control As Control = Nothing
    Dim controlName As String = page.Request.Params("__EVENTTARGET")
    If (Not String.IsNullOrEmpty(controlName)) Then
        control = page.FindControl(controlName)
    Else
        Dim controlId As String
        Dim foundControl As Control
        For Each ctl As String In page.Request.Form
            If (ctl.EndsWith(".x") Or ctl.EndsWith(".y")) Then
                controlId = ctl.Substring(0, ctl.Length - 2)
                foundControl = page.FindControl(controlId)
            Else
                foundControl = page.FindControl(ctl)
            End If
            If Not (TypeOf foundControl Is Button Or TypeOf foundControl Is ImageButton) Then Continue For
            control = foundControl
            Exit For
        Next
    End If
Return control

C# 語法

public static Control GetPostBackControl(Page page)
{
    Control control = null;
    string controlName = page.Request.Params("__EVENTTARGET");
    if (!string.IsNullOrEmpty(controlName)) {
        control = page.FindControl(controlName);
    } else {
        string controlId = "";
        Control foundControl = null;
        foreach (string ctl in page.Request.Form) {
            if (ctl.EndsWith(".x") | ctl.EndsWith(".y")) {
                controlId = ctl.Substring(0, ctl.Length - 2);
                foundControl = page.FindControl(controlId);
            } else {
                foundControl = page.FindControl(ctl);
            }
            if (!(foundControl is Button | foundControl is ImageButton))
                continue;
            control = foundControl;
            break;
        }
    }
    return control;
}
arrow
arrow

    達達 發表在 痞客邦 留言(0) 人氣()