索引数组超出范围异常

时间:2022-07-31 16:43:37

I try to save the SQL Results in a array and return it back. but i'm getting an exception: array out of range error.

我尝试将SQL结果保存在一个数组中并将其返回。但我得到一个例外:数组超出范围错误。

here is my code:

这是我的代码:

 public BookingUpdate[] getBookingUpdates(string token)
{
    String command = "SELECT b.ID,b.VERANSTALTER, rr.VON ,rr.BIS, b.THEMA, b.STORNO, ra.BEZEICHNUNG from BUCHUNG b JOIN RESERVIERUNGRAUM rr on rr.BUCHUNG_ID = b.ID JOIN RAUM ra on ra.ID = rr.RAUM_ID WHERE b.UPDATE_DATE BETWEEN DATEADD (DAY , -20 , getdate()) AND getdate() AND b.BOOKVERNR = 0";
    SqlConnection connection = new SqlConnection(GetConnectionString());
    BookingUpdate[] bookingupdate = new BookingUpdate[1];
    connection.Open();
    try
    {
        SqlCommand cmd = new SqlCommand(command, connection);
        SqlDataReader rdr = null;
        int count = 0;
        rdr = cmd.ExecuteReader();


            while (rdr.Read())
            {
                DataTable dt = new DataTable();
                dt.Load(rdr);
                count = dt.Rows.Count;
                for (int c = 0; c < count; c++)
                {
                    bookingupdate = new BookingUpdate[c];
                    bookingupdate[c].bookingID = (long)rdr["ID"]; // <---- Error is here
                    bookingupdate[c].fullUserName = rdr["VERANSTALTER"].ToString();
                    bookingupdate[c].newStart = (DateTime)rdr["VON"];
                    bookingupdate[c].newStart = (DateTime)rdr["BIS"];
                    bookingupdate[c].newSubject = rdr["THEMA"].ToString();
                    bookingupdate[c].newlocation = rdr["BEZEICHNUNG"].ToString();
                    if (rdr["STORNO"].ToString() != null)
                    {
                        bookingupdate[c].deleted = true;
                    }
                    else
                    {
                        bookingupdate[c].deleted = false;
                    }

                }

            }

    }

    catch (Exception ex)
    {
        log.Error(ex.Message + "\n\rStackTrace:\n\r" + ex.StackTrace);
    }
    finally
    {
        connection.Close();
    }
    return bookingupdate;
}

What am i missing?

我错过了什么?

9 个解决方案

#1


1  

You appear to be creating and allocating memory for an array with

您似乎正在为数​​组创建和分配内存

bookingupdate = new BookingUpdate[c];

but not actually creating instances of BookingUpdate. When you attempt to set properties on your array element there is no actual BookingUpdate to update - there is only a holder for one.

但实际上并没有创建BookingUpdate的实例。当您尝试在数组元素上设置属性时,没有要更新的实际BookingUpdate - 只有一个持有者。

I'd suggest changing your code to something along the lines of:

我建议将代码更改为以下内容:

...
bookingupdate = new BookingUpdate[count];  // allocates space for the number of BookingUpdates to be created
for (int c = 0; c < count; c++)
{
    bookingupdate[c] = new BookingUpdate(); // create a new instance of BookingUpdate and assign it the array     
    bookingupdate[c].bookingID = (long)rdr["ID"];
    ...

I hope that this helps!

我希望这个对你有用!

#2


2  

bookingupdate = new BookingUpdate[c];
bookingupdate[c].bookingID = (long)rdr["ID"]; 

you are creating an Array of length c, which means it has the Indexes 0 to (c-1) - and then you are out of bounds, when trying to store at Position c.

你正在创建一个长度为c的数组,这意味着它有索引0到(c-1) - 然后当你试图存储在位置c时你就超出界限了。

#3


1  

Imho i would simplify your way to construct that array with Linq:

Imho我将简化你用Linq构建该数组的方法:

BookingUpdate[] bookingupdate = dt.AsEnumerable()
    .Select(r => new BookingUpdate{
        bookingID = r.Field<long>("ID"),
        fullUserName = r.Field<string>("VERANSTALTER"),
        newStart = r.Field<DateTime>("Von"),
        newEnd = r.Field<DateTime>("Bis"), // here was another bug in your originalcode
        newSubject = r.Field<string>("THEMA"),
        newlocation = r.Field<string>("BEZEICHNUNG"),
        deleted = r.Field<string>("STORNO") != null
    })
    .ToArray();

On this way you will not have problems with arrays that are out of bounds.

通过这种方式,您不会遇到超出界限的数组问题。

#4


0  

You accessing the n'th element of an n-Elements array which is out of range, you need to access the n - 1 element.

您访问超出范围的n元素数组的第n个元素,您需要访问n - 1元素。

bookingupdate = new BookingUpdate[c];   // You create an array of 5 elements for example 
bookingupdate[c].bookingID = (long)rdr["ID"]; // Here you access the 5th elements but there are only 4

#5


0  

the problem is related with the size of the array;

问题与数组的大小有关;

 for (int c = 0; c < count; c++)
 {
    bookingupdate = new BookingUpdate[c];
    bookingupdate[c].bookingID = (long)rdr["ID"];

in the previous code, you are creating an array (bookingupdate ) of size 0 at first; then you are trying to insert an item. Even if you somehow manage to skip first one, it will again fail. Just update these lines to the following;

在上面的代码中,您首先要创建一个大小为0的数组(bookingupdate);然后你试图插入一个项目。即使你以某种方式设法跳过第一个,它也会再次失败。只需将这些行更新为以下内容即可;

bookingupdate = new BookingUpdate[count];
for (int c = 0; c < count; c++)
     {        
        bookingupdate[c].bookingID = (long)rdr["ID"];

#6


0  

            for (int c = 0; c < count; c++)
            {
                bookingupdate = new BookingUpdate[c];

Error is at first iteration of this for loop where c is zero. ie, you are trying to create a array of length zero. bookingupdate = new BookingUpdate[0];

错误是此for循环的第一次迭代,其中c为零。即,您正在尝试创建一个长度为零的数组。 bookingupdate = new BookingUpdate [0];

#7


0  

You have initialized an array but not the class itself before calling it. Also your initialization is wrong

在调用之前,您已初始化了一个数组,但不是该类本身。你的初始化也是错误的

count = dt.Rows.Count;
bookingupdate = new BookingUpdate[count];
for (int c = 0; c < count; c++)
{
    bu = new BookingUpdate();
    bu.bookingID = (long)rdr["ID"]; // <---- Error is here
    bu.fullUserName = rdr["VERANSTALTER"].ToString();
    bu.newStart = (DateTime)rdr["VON"];
    bu.newStart = (DateTime)rdr["BIS"];
    bu.newSubject = rdr["THEMA"].ToString();
    bu.newlocation = rdr["BEZEICHNUNG"].ToString();
    if (rdr["STORNO"].ToString() != null)
    {
        bu.deleted = true;
    }
    else
    {
        bu.deleted = false;
    }
    bookingupdate[c] = bu;
}

#8


0  

Arrays has zero based index.

数组具有零基索引。

When you create bookingupdate = new BookingUpdate[c]; your last index would c-1.

当你创建bookingupdate = new BookingUpdate [c];你的最后一个索引是c-1。

You can't access BookingUpdate[c] because it is not exist.

您无法访问BookingUpdate [c],因为它不存在。

Let's say c = 4, that means we definedan array with 4 elements which they are;

假设c = 4,这意味着我们定义了具有4个元素的数组;

BookingUpdate[0]
BookingUpdate[1]
BookingUpdate[2]
BookingUpdate[3]

BookingUpdate[c] would equal BookingUpdate[4] which there is no such an index.

BookingUpdate [c]等于BookingUpdate [4],没有这样的索引。

From MSDN page;

来自MSDN页面;

Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.

数组为零索引:具有n个元素的数组从0到n-1索引。

#9


0  

Use this code

使用此代码

public BookingUpdate[] getBookingUpdates(string token)
{
String command = "SELECT b.ID,b.VERANSTALTER, rr.VON ,rr.BIS, b.THEMA, b.STORNO, ra.BEZEICHNUNG from BUCHUNG b JOIN RESERVIERUNGRAUM rr on rr.BUCHUNG_ID = b.ID JOIN RAUM ra on ra.ID = rr.RAUM_ID WHERE b.UPDATE_DATE BETWEEN DATEADD (DAY , -20 , getdate()) AND getdate() AND b.BOOKVERNR = 0";
BookingUpdate[] bookingupdate;
SqlConnection connection = new SqlConnection(GetConnectionString());

connection.Open();
try
{
    SqlCommand cmd = new SqlCommand(command, connection);
    SqlDataReader rdr = null;
    int count = 0;
    rdr = cmd.ExecuteReader();


        while (rdr.Read())
        {
            DataTable dt = new DataTable();
            dt.Load(rdr);
            count = dt.Rows.Count;
            bookingupdate = new BookingUpdate[count];
            for (int c = 0; c < count; c++)
            {
                bookingupdate[c].bookingID = (long)rdr["ID"]; // <---- Error is here
                bookingupdate[c].fullUserName = rdr["VERANSTALTER"].ToString();
                bookingupdate[c].newStart = (DateTime)rdr["VON"];
                bookingupdate[c].newStart = (DateTime)rdr["BIS"];
                bookingupdate[c].newSubject = rdr["THEMA"].ToString();
                bookingupdate[c].newlocation = rdr["BEZEICHNUNG"].ToString();
                if (rdr["STORNO"].ToString() != null)
                {
                    bookingupdate[c].deleted = true;
                }
                else
                {
                    bookingupdate[c].deleted = false;
                }

            }

        }

}

catch (Exception ex)
{
    log.Error(ex.Message + "\n\rStackTrace:\n\r" + ex.StackTrace);
}
finally
{
    connection.Close();
}
return bookingupdate;

}

#1


1  

You appear to be creating and allocating memory for an array with

您似乎正在为数​​组创建和分配内存

bookingupdate = new BookingUpdate[c];

but not actually creating instances of BookingUpdate. When you attempt to set properties on your array element there is no actual BookingUpdate to update - there is only a holder for one.

但实际上并没有创建BookingUpdate的实例。当您尝试在数组元素上设置属性时,没有要更新的实际BookingUpdate - 只有一个持有者。

I'd suggest changing your code to something along the lines of:

我建议将代码更改为以下内容:

...
bookingupdate = new BookingUpdate[count];  // allocates space for the number of BookingUpdates to be created
for (int c = 0; c < count; c++)
{
    bookingupdate[c] = new BookingUpdate(); // create a new instance of BookingUpdate and assign it the array     
    bookingupdate[c].bookingID = (long)rdr["ID"];
    ...

I hope that this helps!

我希望这个对你有用!

#2


2  

bookingupdate = new BookingUpdate[c];
bookingupdate[c].bookingID = (long)rdr["ID"]; 

you are creating an Array of length c, which means it has the Indexes 0 to (c-1) - and then you are out of bounds, when trying to store at Position c.

你正在创建一个长度为c的数组,这意味着它有索引0到(c-1) - 然后当你试图存储在位置c时你就超出界限了。

#3


1  

Imho i would simplify your way to construct that array with Linq:

Imho我将简化你用Linq构建该数组的方法:

BookingUpdate[] bookingupdate = dt.AsEnumerable()
    .Select(r => new BookingUpdate{
        bookingID = r.Field<long>("ID"),
        fullUserName = r.Field<string>("VERANSTALTER"),
        newStart = r.Field<DateTime>("Von"),
        newEnd = r.Field<DateTime>("Bis"), // here was another bug in your originalcode
        newSubject = r.Field<string>("THEMA"),
        newlocation = r.Field<string>("BEZEICHNUNG"),
        deleted = r.Field<string>("STORNO") != null
    })
    .ToArray();

On this way you will not have problems with arrays that are out of bounds.

通过这种方式,您不会遇到超出界限的数组问题。

#4


0  

You accessing the n'th element of an n-Elements array which is out of range, you need to access the n - 1 element.

您访问超出范围的n元素数组的第n个元素,您需要访问n - 1元素。

bookingupdate = new BookingUpdate[c];   // You create an array of 5 elements for example 
bookingupdate[c].bookingID = (long)rdr["ID"]; // Here you access the 5th elements but there are only 4

#5


0  

the problem is related with the size of the array;

问题与数组的大小有关;

 for (int c = 0; c < count; c++)
 {
    bookingupdate = new BookingUpdate[c];
    bookingupdate[c].bookingID = (long)rdr["ID"];

in the previous code, you are creating an array (bookingupdate ) of size 0 at first; then you are trying to insert an item. Even if you somehow manage to skip first one, it will again fail. Just update these lines to the following;

在上面的代码中,您首先要创建一个大小为0的数组(bookingupdate);然后你试图插入一个项目。即使你以某种方式设法跳过第一个,它也会再次失败。只需将这些行更新为以下内容即可;

bookingupdate = new BookingUpdate[count];
for (int c = 0; c < count; c++)
     {        
        bookingupdate[c].bookingID = (long)rdr["ID"];

#6


0  

            for (int c = 0; c < count; c++)
            {
                bookingupdate = new BookingUpdate[c];

Error is at first iteration of this for loop where c is zero. ie, you are trying to create a array of length zero. bookingupdate = new BookingUpdate[0];

错误是此for循环的第一次迭代,其中c为零。即,您正在尝试创建一个长度为零的数组。 bookingupdate = new BookingUpdate [0];

#7


0  

You have initialized an array but not the class itself before calling it. Also your initialization is wrong

在调用之前,您已初始化了一个数组,但不是该类本身。你的初始化也是错误的

count = dt.Rows.Count;
bookingupdate = new BookingUpdate[count];
for (int c = 0; c < count; c++)
{
    bu = new BookingUpdate();
    bu.bookingID = (long)rdr["ID"]; // <---- Error is here
    bu.fullUserName = rdr["VERANSTALTER"].ToString();
    bu.newStart = (DateTime)rdr["VON"];
    bu.newStart = (DateTime)rdr["BIS"];
    bu.newSubject = rdr["THEMA"].ToString();
    bu.newlocation = rdr["BEZEICHNUNG"].ToString();
    if (rdr["STORNO"].ToString() != null)
    {
        bu.deleted = true;
    }
    else
    {
        bu.deleted = false;
    }
    bookingupdate[c] = bu;
}

#8


0  

Arrays has zero based index.

数组具有零基索引。

When you create bookingupdate = new BookingUpdate[c]; your last index would c-1.

当你创建bookingupdate = new BookingUpdate [c];你的最后一个索引是c-1。

You can't access BookingUpdate[c] because it is not exist.

您无法访问BookingUpdate [c],因为它不存在。

Let's say c = 4, that means we definedan array with 4 elements which they are;

假设c = 4,这意味着我们定义了具有4个元素的数组;

BookingUpdate[0]
BookingUpdate[1]
BookingUpdate[2]
BookingUpdate[3]

BookingUpdate[c] would equal BookingUpdate[4] which there is no such an index.

BookingUpdate [c]等于BookingUpdate [4],没有这样的索引。

From MSDN page;

来自MSDN页面;

Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.

数组为零索引:具有n个元素的数组从0到n-1索引。

#9


0  

Use this code

使用此代码

public BookingUpdate[] getBookingUpdates(string token)
{
String command = "SELECT b.ID,b.VERANSTALTER, rr.VON ,rr.BIS, b.THEMA, b.STORNO, ra.BEZEICHNUNG from BUCHUNG b JOIN RESERVIERUNGRAUM rr on rr.BUCHUNG_ID = b.ID JOIN RAUM ra on ra.ID = rr.RAUM_ID WHERE b.UPDATE_DATE BETWEEN DATEADD (DAY , -20 , getdate()) AND getdate() AND b.BOOKVERNR = 0";
BookingUpdate[] bookingupdate;
SqlConnection connection = new SqlConnection(GetConnectionString());

connection.Open();
try
{
    SqlCommand cmd = new SqlCommand(command, connection);
    SqlDataReader rdr = null;
    int count = 0;
    rdr = cmd.ExecuteReader();


        while (rdr.Read())
        {
            DataTable dt = new DataTable();
            dt.Load(rdr);
            count = dt.Rows.Count;
            bookingupdate = new BookingUpdate[count];
            for (int c = 0; c < count; c++)
            {
                bookingupdate[c].bookingID = (long)rdr["ID"]; // <---- Error is here
                bookingupdate[c].fullUserName = rdr["VERANSTALTER"].ToString();
                bookingupdate[c].newStart = (DateTime)rdr["VON"];
                bookingupdate[c].newStart = (DateTime)rdr["BIS"];
                bookingupdate[c].newSubject = rdr["THEMA"].ToString();
                bookingupdate[c].newlocation = rdr["BEZEICHNUNG"].ToString();
                if (rdr["STORNO"].ToString() != null)
                {
                    bookingupdate[c].deleted = true;
                }
                else
                {
                    bookingupdate[c].deleted = false;
                }

            }

        }

}

catch (Exception ex)
{
    log.Error(ex.Message + "\n\rStackTrace:\n\r" + ex.StackTrace);
}
finally
{
    connection.Close();
}
return bookingupdate;

}