I have a listview and a button next to it that uses the selected item to do an action. If the user doesn't make a selection, but clicks on the button they are told to make a selection first.
What I have below works, but is there a way where the calling method doesn't have to have the "if(not selected)" return statement? I want to just call "selectionFound()" method from other events that rely on the listview? I'd like the selectionFound method to exit out of not just itself, but also the calling method and return control back to the user. So instead of return true/false as below, I'd like to have just return or whatever keyword.
private void deleteData()
{
// if nothing selected, warn user and return control
if(!selectionFound()) return;
.....
}
private bool selectionFound()
{
// make sure user selected an item from listview, warn and exit if not
if (lvwInventory.SelectedIndex == -1)
{
MessageBox.Show("Please select an item first");
return false;
}
else
return true;
}
Aside from returning a flag as per your example, the closest you're going to get is to throw an exception, as that's the only mechanism I'm aware of that can jump entire stack frames without letting methods finish executing.
EDIT: And you should not use exceptions for this purpose, since they indicate that something exceptional happened.
Why even put this in code? In the xaml you can disable the button if an item isn't selected.
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<ListView x:Name="listy">
<ListViewItem>one
</ListViewItem>
<ListViewItem>two
</ListViewItem>
<ListViewItem>three
</ListViewItem>
</ListView>
<Button Grid.Row="1" Content="Clicky">
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedItem, ElementName=listy}" Value="{x:Null}">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</Grid>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With