我试图测试我的列表是否正在从数据库收集数据,但是当我尝试获取消息框以从列表中打印邮政编码时,它给了我例外“System.ArgumentOutOfRangeException:”索引超出范围。必须为非负数且小于集合的大小。
参数名称:索引'`
这是我编写和正在使用的方法
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.GetOrdinal("postcode").ToString());
}
connect.Close();
return postcodes;
}
列表postcodes
在我的代码中是这样定义的List<string> postcodes = new List<string>();
这是我尝试测试邮政编码集合的方法
private void Button_Click1(object sender, RoutedEventArgs e)
{
string test1 = postcodes[1];
MessageBox.Show(test1);
}
假设string test1 = postcodes[1];
是导致问题的行,显然索引 1 不存在于postcodes
list.
请记住,索引 1 指的是secondC# 中的元素。如果您只有一个邮政编码,或者您想参考first元素,您需要使用:
string test1 = postcodes[0];
您还可以检查索引 1 处的邮政编码是否存在:
if (postcodes.Count >= 2)
// postcodes[1] definitely exists
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)