【问题标题】:What is causing my argument out of range exception? [duplicate]是什么导致我的论点超出范围异常? [复制]
【发布时间】:2019-12-10 14:33:19
【问题描述】:

我试图测试我的列表是否正在从数据库中收集数据,但是当我尝试获取一个消息框以从列表中打印一个邮政编码时,它给了我一个例外 `System.ArgumentOutOfRangeException: 'Index was out of range。必须为非负数且小于集合的大小。

参数名称:索引'`

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

        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&lt;string&gt; postcodes = new List&lt;string&gt;();

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

        private void Button_Click1(object sender, RoutedEventArgs e)

    {

        string test1 = postcodes[1];

        MessageBox.Show(test1);

    }

【问题讨论】:

  • 这不是c
  • @SouravGhosh 感谢 m8
  • 如果你的目标是索引 1; postcodes[1],您实际上将针对第二个元素。你知道吗? (第一个使用postcodes[0]
  • 旁注:使用using 语句来处理实现IDisposable 的对象...
  • 我们尝试了第一个索引postcodes[0],这也给出了同样的错误。关于索引超出范围。在我们看不到的GetPostcodes 方法中检索邮政编码的方式是否存在问题?

标签: c# wpf


【解决方案1】:

假设string test1 = postcodes[1]; 是导致问题的行,显然postcodes 列表中不存在索引1。

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

string test1 = postcodes[0];

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

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

【讨论】:

    猜你喜欢
    • 2012-02-16
    • 2014-09-08
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    相关资源
    最近更新 更多