是什么导致我的参数超出范围异常?

时间:2019-12-10 14:33:19

标签: c# wpf

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

参数名称:index'`

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

        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);

    }

1 个答案:

答案 0 :(得分:0)

假设<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table class="messages-list-table"> <tr> <th class="message-name">Name</th> <th class="message-body">Message</th> </tr> <tr id="1"> <td class="message-name">Mike</td> <td class="message-body" data-code="5652c0bcc277bf4c039686d">This is the same message</td> </tr> <tr id="2"> <td class="message-name">John</td> <td class="message-body" data-code="5652c0bcc277bf4c039686d">This is the same message</td> </tr> <tr id="3"> <td class="message-name">Steve</td> <td class="message-body" data-code="725c1424b123dabc3">This is the same messages</td> </tr> <tr id="5"> <td class="message-name">Michael</td> <td class="message-body" data-code="5652c0bcc277bf4c039686d">This is the same message</td> </tr> <tr id="6"> <td class="message-name">Alfredo</td> <td class="message-body" data-code="725c1424b123dabc3">This is the same messages</td> </tr> <tr id="8"> <td class="message-name">Paul</td> <td class="message-body" data-code="8cbsh7364hd94d8">Totally different message</td> </tr> </table>是引起问题的那一行,显然string test1 = postcodes[1];列表中不存在索引1。

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

postcodes

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

string test1 = postcodes[0];