我正在编写一个程序,使人们可以输入邮政编码,并显示与输入的邮政编码有多远的不同医疗服务。
邮政编码应该存储在列表中,但是我不知道如何检查列表是否被填充。
谁能给我任何想法。
这是列表
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;
}
这是一个测试器按钮,但是它不起作用
private void Button_Click1(object sender, RoutedEventArgs e)
{
var test1 = GetPostcodes("gpSurgery").ToString();
MessageBox.Show(test1);
}
GetPostcodes
方法应在每次调用时创建一个新的List<string>
,而不是重新使用全局变量:
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;
}
在“测试”中,如果要确定列表中的项目数,可以简单地检查列表的Count属性的值:
private void Button_Click1(object sender, RoutedEventArgs e)
{
var test1 = GetPostcodes("gpSurgery");
MessageBox.Show(test1.Count);
}
[您需要做的是检查GetpostCodes返回的列表。不要将其转换为String,因为该函数不适用于Lists。您必须正确地将列表转换为其相应的字符串。
GetPostcodes返回一个列表。使用该列表检查其计数。
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.
}
}