0

i am getting the error "index was outside the bounds of the array" when running the program, idk why. I am not able to find the issue.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

    enter code here

namespace WebService
{
    public class DataHelper
    {
        public static SqlConnection GetConnection()
        {
            SqlConnection con = new SqlConnection("Integrated Security = True; Server = localhost; Trusted_Connection= yes; database= Programkonstruktion; ");
            con.Open();
            return con;

        }

        //Create new method to get CustomerInfo
        public static List<String[]> getCustomerInfo(int CustId)
        {
            List<String[]> lista = new List<string[]>();

            using (SqlConnection con = GetConnection())
            {

                //SQLCommand
                SqlCommand cmd = new SqlCommand("Select * From Customer", con);

                //To read from SQL Server
                SqlDataReader dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    string[] row = new string[dr.FieldCount];
                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        row[i] = dr.GetValue(i + 1).ToString();
                    }
                    lista.Add(row);
                }
                return lista;
            }
        }

I am happy for all the answers you can give me! best regards } }

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • Can you tell us which line exactly is throwing the error? – AMINCHAR Feb 26 '18 at 15:44
  • Maybe because the index your trying to access is non-existent? Which part of the code produces the error? – Helquin Feb 26 '18 at 15:44
  • Whereabouts is the exception being thrown? Run the code through a debugger and see which line the stack pointer was on when the problem occurred, see what values you have for your indexes, and how big the collections are that you're trying to index in to – LordWilmore Feb 26 '18 at 15:45
  • 2
    I recommend using a breakpoint and stepping through your code but your problem is `row[i] = dr.GetValue(i + 1).ToString();` should be `row[i] = dr.GetValue(i).ToString();` – Jared Stroebele Feb 26 '18 at 15:46
  • 1
    `dr.GetValue(i+1)`? Why `i+1`? This is index zero-based, too. – René Vogt Feb 26 '18 at 15:46
  • The line that is not working is: row[i] = dr.GetValue(i + 1).ToString(); – Lukas Lyth Feb 26 '18 at 15:50
  • So what is the value of `i` when the error occurs? Why do you you have `i + 1` inside the `GetValue` call? – Chris Dunaway Feb 26 '18 at 17:17
  • As an aside, you appear to be returning a list of arrays. This seems unusual. – peterG Feb 26 '18 at 18:34

0 Answers0