-3

Im writing a program that allows people to input a postcode and get different medical services displayed with how far away they are from the inputted postcode.

The postcodes are meant to be stored in a list however I do not know how to check if the list gets populated.

could anyone give me any ideas.

This is the list

 private List<string> GetPostcodes(string table)
    {
        connect = new MySqlConnection(connectionString);
        connect.Open();
        string selectString = "select postcode from " + table;

        MySqlCommand cmd = new MySqlCommand(selectString,connect);
        reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            postcodes.Add(reader.GetString("postcode"));
        }
        connect.Close();

        return postcodes;
    }

And this is a tester button however it doesnt work

 private void Button_Click1(object sender, RoutedEventArgs e)
    {
        var test1 = GetPostcodes("gpSurgery").ToString();
        MessageBox.Show(test1);

    }
gunr2171
  • 16,104
  • 25
  • 61
  • 88

2 Answers2

2

The GetPostcodes method should create a new List<string> on each invocation instead of reusing a global variable:

private List<string> GetPostcodes(string table)
{
    List<string> postcodes = new List<string>();
    using (var connect = new MySqlConnection(connectionString))
    {
        connect.Open();
        string selectString = "select postcode from " + table;
        using (MySqlCommand cmd = new MySqlCommand(selectString, connect))
        {
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    postcodes.Add(reader.GetString("postcode"));
                }
            }
        }
    }
    return postcodes;
}

In the "test", you could simply check the value of the Count property of the list if you want to determine the number of items in it:

private void Button_Click1(object sender, RoutedEventArgs e)
{
    var test1 = GetPostcodes("gpSurgery");
    MessageBox.Show(test1.Count);

}
mm8
  • 163,881
  • 10
  • 57
  • 88
1

What you need to do is check the List being returned by the GetpostCodes. Dont convert that to String because that function doesnt work with Lists. You have to correctly convert the list to its corresponding string.

GetPostcodes returns a list. Use that list to check its Count.

 private void Button_Click1(object sender, RoutedEventArgs e)
    {
        var test1 = GetPostcodes("gpSurgery");
        if (test1.Count > 0) // <---- Check the Count here
        {
            MessageBox.Show(string.Join(",", test1)); // <-- Display the list
        }
        else
        {
            MessageBox.Show("Nothing found"); // <-- Shows nothing found.
        }
    }
Jawad
  • 11,028
  • 3
  • 24
  • 37