How to disable Save button in LightSwitch screen based on role

March 05, 2012

There could be time, that your customer, or user can have quite logical requirement :

Please, disable Save button on whole screen according to role. You as dev will say OK, why not. Then you will come to Lightswitch IDE , right click Save button to create Can Run event handler and you will see (screaming, swearing / insert appropriate) something like this :

save button context menu lightswitch

All custom added buttons have also Can Execute option, but not out of box (save, refresh) buttons.

First thing – please consider also rights on datasource. I mean

partial void SaveChanges_CanExecute(ref bool result)

on each datasource.

This is where you should check rights and say no to user in case you don’t want him to save changes. But this will not make Save button disable him self automatically. It will only display note to user, he can’t save what he changed. It’s also server side check and thus little more safer (no more client side hacks).

This is how whole app will look when you have check on model :

datasource check

But how to say disable to Save button in code?

For example like this :

public partial class EditableUsersGrid
{
partial void EditableUsersGrid_InitializeDataWorkspace(List<IDataService> saveChangesTo)
{
    if (!this.Application.User.HasPermission(Permissions.CanSaveUsers))
    {
        saveChangesTo.Clear();
    }
}
}

I’m checking for a permission and then I’m clearing collection of datasources for this particular screen. I had this idea, because I was dealing with problem of two datasources on one screen and InitializeDataWorkspace is the event where you can add another datasources needed. So why not to try clear them out? 🙂

This is the result : disabled Save button :

screen check

As always here is the demo app to play with and feel free to ask if you have any questions :

https://skydrive.live.com/redir.aspx?cid=78a5783de37d2ebe&resid=78A5783DE37D2EBE!1801&parid=78A5783DE37D2EBE!1779


Profile picture

Written by Dušan Roštár - the "mr edge case" guy
my twitter : rostacik, my linkedin : rostar, drop me an email : here