Checking search buttons on click There are 3 search fields, and at least one must be filled out. When the search button is clicked the search fields are checked, if none are filled in show the error window with the error message for this error. If at least one field is filled in get a code based on the search criteria. If the code was not successfully retrieved show same error window but with the error message for this error.

The code I have works fine for this except that it looks verbose and I am repeated the code in the else statements except for the unique error messages. How can this be improved?

private void searchButton_Click(object sender, RoutedEventArgs e)
{
    searchCriteria.Clear();
    searchCriteria.Add(townSearchTextbox.Text);
    searchCriteria.Add(countySearchTextbox.Text);
    searchCriteria.Add(postcodeSearchTextbox.Text);

    if (isValidSearchCriteria(searchCriteria))
    {
        formatSearchCriteria(searchCriteria);
        set.updateWOEID(searchCriteria);
        if (set.WOEID.Length &gt; 0)
        {
            // continue
        }
        else
        {
            // display any errors in the error window
            Error errorWindow = new Error();
            errorWindow.Show();
            errorWindow.errorMessage.Text = "Error: Could not retrieve WOEID, please try again.";
        }
    }
    else
    {
        // display any errors in the error window
        Error errorWindow = new Error();
        errorWindow.Show();
        errorWindow.errorMessage.Text = "Error: Please provide one or more search criteria.";
    }
}
Create a method:

private void DisplayError(String errorMessage) 
{
    // display any errors in the error window
    Error errorWindow = new Error();
    errorWindow.Show();
    errorWindow.errorMessage.Text = errorMessage;
}


Then you can do

private void searchButton_Click(object sender, RoutedEventArgs e)
{
    searchCriteria.Clear();
    searchCriteria.Add(townSearchTextbox.Text);
    searchCriteria.Add(countySearchTextbox.Text);
    searchCriteria.Add(postcodeSearchTextbox.Text);

    if (isValidSearchCriteria(searchCriteria))
    {
        formatSearchCriteria(searchCriteria);
        set.updateWOEID(searchCriteria);
        if (set.WOEID.Length &gt; 0)
        {
            // continue
        }
        else
        {
            DisplayError("Error: Could not retrieve WOEID, please try again.");
        }
    }
    else
    {
        DisplayError("Error: Please provide one or more search criteria.");
    }
}


Of course, the next step if you need it would be to use Exceptions instead.  Yes, I know this is for Java, but it shows why.