简体   繁体   中英

How to stop popup if selectedItem is null

How to stop program when selectedItem is null? I want to stop program because Show method return me selectedItem as null and I got empty in my List. I just want to stop program if selectedItem is null?

public static string Show(IList<ListItem> items, string title)
{
    ItemsPopupWindow instance = new ItemsPopupWindow(items, title);
    instance.ShowDialog();
    if (instance.selectedItem == null)
    {

    }
    return instance.SelectedItem;
} 

If you want to "close" the program or stop it. Id just do this.

string retVal = Foo.Show('YourList', 'YourTitle');
if(string.IsNullOrEmpty(retVal))
{
    // if you have a wpf application
    System.Windows.Application.Current.Shutdown();

    // if you have a winforms application
    Application.Exit();
}

You can throw an exception.

public static string Show(IList<ListItem> items, string title)
{
    ItemsPopupWindow instance = new ItemsPopupWindow(items, title);
    instance.ShowDialog();
    if (instance.selectedItem == null)
    {
        throw new Exception("The selected item is null.");
    }
    return instance.SelectedItem;
} 

This will stop the execution of this method. The calling method can have a try / catch block that can handle this. If the calling method does not handle this thrown exception by catching it, it will go to the method that called that method. If no method ever handles it, the program will crash.

public static void Main() {
    try {
         Show(new List<ListItem>(), "");
    }
    catch(Exception ex){
        Console.Write("An error occurred: " + ex.Message);
    }
}

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM