How to fire a button event from inside a repeater?

大憨熊 提交于 2019-12-05 06:45:10

问题


I have done my research but can't find an efficient way to do the following in VB:

  • Each button should fire the same event.
  • The button event saves every repeater item and so each event is not unique.

I am aware I can use the ItemCommand option but have not been able to get it working as desired.

ASP.NET

Inside Repeater Item

<asp:Button ID="btnSave" RunAt="Server"/>

VB.NET

Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    sqlConn.Open()
        For Each Item As RepeaterItem In rpt.Items
        ...
        Next
    sqlConn.Close()
End Sub

回答1:


Edit:

After some research here on SO, I found that others events than ItemCommand are not caught by Asp:Repeater, as FlySwat said on his answer. So you'll need to write your VB.NET code like this:

First, declare the ItemCommand event on your page with something like this:

Protected Sub rpt_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles rpt.ItemCommand
    If e.CommandName = "Save" Then
        'Save
    End If
End Sub

Then, on Asp:Button markup inside the Asp:Repeater, you must set its CommandName property like this:

<Asp:Button ID="btnSave" runat="server" CommandName="Save" UseSubmitBehavior="false"/>

Take a look here to learn more about the UseSubmitBehavior.

Try it.




回答2:


When the button is inside a Repeater template, you need to add OnClick event, you can add event on ItemDataBound event of the Repeater control.

Your .aspx code will look something like this:

 <asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <asp:Button  ID="btnSave" runat="server" Text="SomeText" />
    </ItemTemplate>
</asp:Repeater>

code-behind

void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == Repeater1.AlternatingItem || e.Item.ItemType == Repeater1.Item)
    {
        var btn = e.Item.FindControl("btnSave") as Button;
        if (btn != null)
        {  // adding button event 
            btn.Click += new EventHandler(btn_Click);
        }
    }
}

void btn_Click(object sender, EventArgs e)
{
 //write your code 
}

in vb.net

Private Sub Repeater1_ItemDataBound(sender As Object, e As RepeaterItemEventArgs)
    If e.Item.ItemType = Repeater1.AlternatingItem OrElse e.Item.ItemType = Repeater1.Item Then
        Dim btn = TryCast(e.Item.FindControl("btnSave"), Button)
        If btn IsNot Nothing Then
            ' adding button event 
            btn.Click += New EventHandler(btn_Click)
        End If
    End If
End Sub

Private Sub btn_Click(sender As Object, e As EventArgs)
    'write your code 
End Sub


来源:https://stackoverflow.com/questions/20540675/how-to-fire-a-button-event-from-inside-a-repeater

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!