Wednesday, 10 February 2010

AspxGridview Custom buttons and actions

This post is to describe the process of creating a custom button in a Dev Express AspxGridview and to create a code behind event that will handle it.





The example I am going to use is a simple 'Admin' function which will return a list of Role IDs that the user has. We also want to be able to give our Admins the ability to remove one or more roles from the user's profile.





From a technical side, we will be using an ASPXGridview grid databound to a SQL database, as shown below








To Create the "Remove" button, you will need to add a CustomButton column, which inherits from the GridViewCommandColumn class. This can be done by switching to the ASPX Source view, and adding the following between your <column> tags


<dxwgv:GridViewCommandColumn VisibleIndex="0">

        <
CustomButtons>

            <
dxwgv:GridViewCommandColumnCustomButton   ID="Remove" Text="Remove">

            </
dxwgv:GridViewCommandColumnCustomButton>

        </
CustomButtons>

</
dxwgv:GridViewCommandColumn>

The entire code for the Grid is :

 

<dxwgv:ASPxGridView runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" ID="gridUserRoles" EnableCallBacks="False"><Columns>
    <dxwgv:GridViewCommandColumn VisibleIndex="0">
        <CustomButtons>
            <dxwgv:GridViewCommandColumnCustomButton ID="Remove" Text="Remove">
            </dxwgv:GridViewCommandColumnCustomButton>
        </CustomButtons>
    </dxwgv:GridViewCommandColumn>
    <dxwgv:GridViewDataTextColumn FieldName="RoleID" VisibleIndex="1">
    </dxwgv:GridViewDataTextColumn>
</Columns>
</dxwgv:ASPxGridView>

Next -


We need to define the Event in the code behind. Create a new CustomButtonCallBack Method, which will serve as a handler for any custom actions that fire.


Finally, we use the Event Args of the Gridview custom button, to find our newly created button. The Event args are referenced when then new CustomButtonCallBack method is created, so we dont even need to worry about creating that.


Protected Sub gridUserRoles_CustomButtonCallback(ByVal sender As Object, ByVal e As DevExpress.Web.ASPxGridView.ASPxGridViewCustomButtonCallbackEventArgs) Handles gridUserRoles.CustomButtonCallback

       If e.ButtonID <> "Remove" Then
           Return

     Else

    ‘Code for removing users role


1 comment:

  1. Dear Sir

    Thank you very much for your suggestion ^^

    ReplyDelete