在ASP.Net DetailsView图像按钮OnClick事件处理程序中传递参数

时间:2013-01-28 18:49:30

标签: asp.net vb.net onclick parameter-passing detailsview

是否可以将ASP.Net图像按钮OnClick事件处理程序中的参数发送到代码隐藏文件?

在DetailsView中,我们为编辑模板的每周的每一天都有这个标记,并且在插入模板的另一堆编码之上:

<EditItemTemplate>
    <asp:ImageButton 
        ID="ImageButtonEditDayOfWeekMonday" 
        runat="server" 
        ImageUrl='<%# getCheckboxImageToDisplay(Eval("DayOfWeekMonday"))%>' 
        Height="15"
        Width="15" 
        OnClick="ImageButtonEditDayOfWeekMonday_Click"
        CausesValidation="False">
    </asp:ImageButton>
</EditItemTemplate>

代码隐藏文件中的处理程序:

Protected Sub ImageButtonEditDayOfWeekTuesday_Click(sender As Object, e As ImageClickEventArgs)

    Dim imgTheImageButton As New ImageButton

    imgTheImageButton = DetailsView.FindControl("ImageButtonEditDayOfWeekTuesday")

    If imgTheImageButton.ImageUrl = "../../Images/checked.png" = True Then

        imgTheImageButton.ImageUrl = "../../Images/unchecked.png"
        LabelCheckBoxTuesday.Text = False
    Else

        imgTheImageButton.ImageUrl = "../../Images/checked.png"
        LabelCheckBoxTuesday.Text = True
    End If
End Sub

这相当于很多编码。

是否可以创建单个处理程序并像这样调用它?

OnClick="ImageButtonDayOfWeek_Click("Monday", "Edit")

所有处理程序之间的唯一区别是:

imgTheImageButton = DetailsView.FindControl("ImageButtonEditDayOfWeekTuesday")

在单个处理程序中使用一堆if语句并使用相应的“ID”放在DetailsView.FindControl中会很好。

1 个答案:

答案 0 :(得分:0)

在ImageButton中,添加一个CommandArgument属性:

<EditItemTemplate>
<asp:ImageButton 
    ID="ImageButtonEditDayOfWeekMonday" 
    runat="server" 
    ImageUrl='<%# getCheckboxImageToDisplay(Eval("DayOfWeekMonday"))%>' 
    Height="15"
    Width="15" 
    OnClick="ImageButtonEditDayOfWeekMonday_Click"
    CommandArgument='<%# Eval("DayOfWeekMonday") %>'
    CausesValidation="False">
</asp:ImageButton>

然后在您的代码隐藏中:

Protected Sub ImageButtonEditDayOfWeekTuesday_Click(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs)

    //e.CommandArgument should contain the actual value of DayOfWeekMonday
    Dim arg As String = e.CommandArgument.ToString()

End Sub