是什么导致我的论点超出范围异常? [英] What is causing my argument out of range exception?

查看:64
本文介绍了是什么导致我的论点超出范围异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图测试我的列表是否正在从数据库中收集数据,但是当我尝试获取一个消息框来打印列表中的邮政编码时,它给了我一个例外,即`System.ArgumentOutOfRangeException:'索引超出范围.必须为非负数并且小于集合的大小.

参数名称:index'`

这是我已经编写并正在使用的方法

 私有列表< string>GetPostcodes(字符串表){connect =新的MySqlConnection(connectionString);connect.Open();string selectString =从" +表中选择邮政编码;MySqlCommand cmd =新的MySqlCommand(selectString,connect);reader = cmd.ExecuteReader();而(reader.Read()){postcodes.Add(reader.GetOrdinal("postcode").ToString());}connect.Close();返回邮政编码;} 

列表邮政编码是在我的代码中定义的,例如 List< string>邮政编码=新列表< string>();

这是我如何尝试测试邮政编码的集合

 私有void Button_Click1(对象发送者,RoutedEventArgs e){字符串test1 =邮政编码[1];MessageBox.Show(test1);} 

解决方案

假定 string test1 = postcodes [1]; 是引起问题的行,显然邮政编码列表.

请记住,索引1引用了C#中的 second 元素.如果您只有一个邮政编码,或者要引用 first 元素,则需要使用:

  string test1 =邮政编码[0]; 

您还可以检查索引1处的邮政编码是否存在:

  if(postcodes.Count> = 2)//邮政编码[1]确实存在... 

im trying to test if my list is collecting data from a database but when i try to get a message box to print a postcode from the list it gives me the exeption `System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.

Parameter name: index'`

here are the methods which i have written and am using

        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;

    }

the list postcodes is defined earlier in my code like this List<string> postcodes = new List<string>();

and here is how im trying to test the collection of the postcodes

        private void Button_Click1(object sender, RoutedEventArgs e)

    {

        string test1 = postcodes[1];

        MessageBox.Show(test1);

    }

解决方案

Presuming that string test1 = postcodes[1]; is the line causing the issue, clearly index 1 does not exist in the postcodes list.

Remember that index 1 refers to the second element in C#. If you only have one postcode, or you meant to refer to the first element, you need to use:

string test1 = postcodes[0];

You could also check to see whether the postcode at index 1 exists:

if (postcodes.Count >= 2)
    // postcodes[1] definitely exists
    ...

这篇关于是什么导致我的论点超出范围异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆