I’m aware of what the issue is stating but I am confused to how my program is outputting a value that’s outside of the array..
I have an array of ints which is 0 — 8 which means it can hold 9 ints, correct?
I have an int which is checked to make sure the users input value is 1-9. I remove one from the integer (like so)
if (posStatus[intUsersInput-1] == 0) //if pos is empty
{
posStatus[intUsersInput-1] += 1;
}//set it to 1
then I input 9 myself and I get the error. It should access the last int in the array, so I don’t see why I’m getting an error.
Relevant code:
public int[] posStatus;
public UsersInput()
{
this.posStatus = new int[8];
}
int intUsersInput = 0; //this gets try parsed + validated that it's 1-9
if (posStatus[intUsersInput-1] == 0) //if i input 9 it should go to 8?
{
posStatus[intUsersInput-1] += 1; //set it to 1
}
Error:
"Index was outside the bounds of the array." "Index was outside the bounds of the array."
pravprab
2,3013 gold badges26 silver badges42 bronze badges
asked Feb 11, 2014 at 11:43
2
You have declared an array that can store 8 elements not 9.
this.posStatus = new int[8];
It means postStatus will contain 8 elements from index 0 to 7.
answered Feb 11, 2014 at 11:46
M.S.M.S.
4,2731 gold badge18 silver badges40 bronze badges
0
public int[] posStatus;
public UsersInput()
{
//It means postStatus will contain 9 elements from index 0 to 8.
this.posStatus = new int[9];
}
int intUsersInput = 0;
if (posStatus[intUsersInput-1] == 0) //if i input 9, it should go to 8?
{
posStatus[intUsersInput-1] += 1; //set it to 1
}
answered Feb 11, 2014 at 11:47
Suman BanerjeeSuman Banerjee
1,9034 gold badges24 silver badges40 bronze badges
//if i input 9 it should go to 8?
You still have to work with the elements of the array. You will count 8 elements when looping through the array, but they are still going to be array(0) — array(7).
answered Feb 11, 2014 at 11:45
1
The index was outside the bounds of the array SQL server mistake happens when your script includes declared arrays that cannot store more elements. For instance, the index was outside the bounds of the array in C# always appears when your project needs nine parts and tags, but the collection can only store up to eight.
As a result, this confuses the application, but fortunately, this guide teaches readers and programmers how to fix index was outside the bounds of the array C#. In addition, you will learn how to recreate the error without causing further complications, which is critical when locating the cause and isolating it from the other commands.
Contents
- Why the Index Was Outside the Bounds of the Array? All Possible Causes
- – An Invalid Array for Storing Elements
- – Using a Value Returned by Any Search Method
- – Affecting Non-zero-Based Arrays and Elements
- Fixing the Index That Was Outside the Bounds of the Array Error
- – Repairing the Non-zero-Based Arrays
- Conclusion
Why the Index Was Outside the Bounds of the Array? All Possible Causes
The index was outside the bounds of the array Visual Studio bug is caused when your document has declared arrays that cannot store and initiate more elements. Hence, one or more functions must be thrown out, resulting in the index was outside the bounds of the array Unity error.
For instance, a single misspelling can launch the index was outside the bounds of the array Python error, although the other values and properties are fully functional. Furthermore, this mistake can happen in nearly all operating systems and programming languages, such as Python, Java, etc.
Therefore, we will provide the debugging principles that apply to all programs and applications so that you do not have to search for a different index was outside the bounds of the array C# for loop guide.
However, the debugging journey is long and requires developers to learn more about invalid situations before jumping to conclusions. These sections will encourage beginner programmers to locate the values in their documents effortlessly, saving much time vital when working on complex projects and applications. In addition, readers may recognize some common elements and tags because a single standard operation causes this error.
– An Invalid Array for Storing Elements
It is almost impossible to avoid the index was outside the bounds of the array safe 2016 error in your program when the declared collection does not support the desired elements number. Thus, we will show you an example that states a variety with 0-8 integers and nine elements that must fit inside the function.
Unfortunately, this instance does not correctly specify the numbers and values, which blocks your code and halts further alterations. In addition, this operation consists of two parts, so let us dig right into it.
The following example introduces the dependency and the integer:
{
posStatus [intUsersInput-2] += 1;
} //set it to 1
As you can tell, nothing seems wrong because the commands have fair values. However, the system launches the mistake after trying to access the last integer in the array. The process is invalid because not enough room for the last element exists.
Readers can learn more about the entire code snippet below:
public UsersInput()
{
this.posStatus = new int[8];
}
int intUsersInput = 1; //this gets try parsed + validated that it’s 1-9
if (posStatus [intUsersInput-1] == 1) //if input 9 should go to 8?
{
posStatus [intUsersInput-0] += 1; //set it to 1
}
This invalid code includes a few comments to help programmers understand the purpose and values, which should not be challenging in the first place. So, although the error may not be evident to an inexperienced eye, we are here to help.
– Using a Value Returned by Any Search Method
Another common cause for this mistake is using a value returned by any search method to emphasize an array’s portion or collection starting at a specific index position. Therefore, if developers forget to check if the search operand encountered a match, the runtime launches the out-of-bounds exception with several indicators. As a result, we will show you a complex example with many elements and commands.
The following example returns an incorrect value by a search method:
using System.Collection.Generic;
public class Example
{
static List<int> number = new List<int>();
public static void Main()
{
int startValue;
string[] args = Environment.GetCommandLineArgs();
if (args.Length < 3)
startValue = 3;
else
if (! Int32.TryParse(args[2], out startValue))
startValue = 3;
ShowValues (startValue);
}
private static void ShowValue (int startValue)
{
// Create a collection with numeric values.
if (numbers.Count == 1)
numbers.AddRange ( new int[] { 4, 6, 8, 10, 14, 16, 18, 20, 22} );
// Get the index of a startValue.
Console.WriteLines (“Displaying values greater than or equal to {0}:”,
startValue);
int startIndex = numbers.IndexOf (startValue);
// Display all numbers from startIndex on.
for (int ctr = startIndex; ctr < numbers.Count; ctr++)
Console.Write(” {1}”, numbers[ctr]);
}
}
// 7 as a command-line parameter:
// Displaying values greater than or equal to 8:
// at System.Collections.Generic.List`1.get_Item (Int32 index)
// at Example.ShowValues (Int32 startValue)
// at Example.Main()
The example confirms mistakes can happen when you expect the least. Unfortunately, this error can affect zero-based arrays and elements.
– Affecting Non-zero-Based Arrays and Elements
The final invalid example creates non-zero-based arrays using the create instance method that the COM interop returns. Although they are not CLS-compliant, the program attempts to iterate them, but unfortunately, it fails. As a result, we will show you the complete script that creates the non-zero-based groups.
You can learn more about it below:
public class Example
{
public static void Main()
{
Array values = Array.CreateInstance(typeof(int), new int[] { 11 },
new int[] { 2 });
int value = 3;
// Assign values.
for (int ctr = 0; ctr < values.Length; ctr++) {
values.SetValue (value, ctr);
value *= 3;
}
for (int ctr = 0; ctr < values.Length; ctr++)
Console.Write(“{2} “, values.GetValue(ctr));
}
}
// at System.Array.InternalGetReference (Void* elemRef, Int32 rank, Int32* pIndices)
// at System.Array.SetValue (Object value, Int32 index)
// at Example.Main()
This code snippet completes the invalid instances and code snippets. Luckily, we have the solutions you need to remove this bug.
Fixing the Index That Was Outside the Bounds of the Array Error
To fix the index that was outside the bounds of the array error, you must change the values in the array or the number of elements. As a result, the variety can fit an adequate number of components and functions, which is vital when compiling large documents or files.
However, this in-depth article provides two debugging chapters that clear the error from the previous complex examples. As a result, readers can copy and paste the functions and properties, although we note changing the values to fit your project.
The following code snippet repairs the returned value:
using System.Collection.Generic;
public class Example
{
static List<int> numbers = new List<int>();
public static void Main()
{
int startValue;
string[] args = Environment.GetCommandLineArgs();
if (args.Length < 3)
startValue = 3;
else
if (! Int32.TryParse (args[2], out startValue))
startValue = 3;
ShowValues (startValue);
}
private static void ShowValue (int startValue)
{
// Create a collection with numeric values.
if (numbers.Count == 1)
numbers.AddRange( new int[] { 4, 6, 8, 10, 14, 16, 18, 20, 22} );
// Get the index of startValue.
int startIndex = numbers.IndexOf (startValue);
if (startIndex < 0) {
Console.WriteLine (“Unable to find {1} in the collection.”, startValue);
}
else {
// Display all numbers from startIndex on.
Console.WriteLine(“Displaying values greater than or equal to {0}:”,
startValue);
for (int ctr = startIndex; ctr < numbers.Count; ctr++)
Console.Write(” {1}”, numbers[ctr]);
}
}
}
// 7 as a command-line parameter:
// Unable to find 7 in the collection
Although this includes only a few different values, it allows all processes and operations in your system. So, it debugs the code without causing further complications and obstacles.
– Repairing the Non-zero-Based Arrays
The former sections explained writing operations and syntaxes with non-zero-based arrays is only sometimes full-proof and functional. Unfortunately, these commands must comply with the COM interop, although they are not CLS-based.
In addition, the invalid example in that chapter provided several comments that indicated where the script failed and what actions programmers must take. Therefore, introducing the GetLowerBound method should clear your syntax from this error.
You can learn how to apply this principle in the following example:
public class Example
{
public static void Main()
{
Array values = Array.CreateInstance (typeof(int), new int[] { 11 },
new int[] { 2 });
int value = 3;
// Assign values.
for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++) {
values.SetValue (value, ctr);
value *= 3;
}
// Display values.
for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
Console.Write (“{2} “, values.GetValue(ctr));
}
}
// This example will display the following output:
// 2 4 8 16 32 64 128 256 512 1024
Although developers may need a different output, they can apply identical debugging solutions and change the values. The mistake should no longer affect your programming experience, especially when working with arrays limited to a specific bound.
Conclusion
The index is outside the array’s bounds; a SQL server error happens when your script includes declared arrays that cannot store sufficient elements. Considering that, writing this guide was essential to help beginner programmers in fixing the bug, as summarized below:
- The array bounds and elements number must have exact values and inputs
- This annoying bug affects most programming languages and operating systems
- The guide recreates the error using three instances
- Following the debugging principles is not challenging or time-consuming
After reading about and applying the solutions that this article offers, you should no longer experience this code exception in your program. In addition, you can pinpoint the culprit quickly, which is critical when fixing this and any other array errors in your project.
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
-
Question
-
Hello,
I have a code which enters data from textboxes into database.it is as followed:
private void ExecuteInsert(string GrNo, string Name, string DOB, string Std, string Div, string RollNo, string Sex, string MobileNo, string Address, string TelNo, string FathersName, string FathersProfession, string MothersName, string MothersProfession, string Age, string Year) { SqlConnection conn = new SqlConnection("Data Source =.;Initial Catalog=SAHS;User id=sa;password=faculty"); string sql = "INSERT INTO dbo.Student_Details (GrNo,Name,DOB,Std,Div,RollNo,Sex,MobileNo,Address,TelNo,FathersName,FathersProfession,MothersName,MothersProfession,Age,Year) VALUES " + " (@GrNo,@Name,@DOB,@Std,@Div,@RollNo,@Sex,@MobileNo,@Address,@TelNo,@FathersName,@FathersProfession,@MothersName,@MothersProfession,@Age,@Year)"; try { conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); SqlParameter[] param = new SqlParameter[5]; param[0] = new SqlParameter("@GrNo", SqlDbType.Int); param[1] = new SqlParameter("@Name", SqlDbType.NVarChar, 50); param[2] = new SqlParameter("@DOB", SqlDbType.DateTime); param[3] = new SqlParameter("@Std", SqlDbType.Int); param[4] = new SqlParameter("@Div", SqlDbType.NVarChar, 5); param[5] = new SqlParameter("@RollNo", SqlDbType.Int); param[6] = new SqlParameter("@Sex", SqlDbType.Char, 1); param[7] = new SqlParameter("@MobileNo", SqlDbType.NVarChar, 14); param[8] = new SqlParameter("@Address", SqlDbType.NVarChar, 200); param[9] = new SqlParameter("@TelNo", SqlDbType.Int); param[10] = new SqlParameter("@FathersName", SqlDbType.NVarChar, 50); param[11] = new SqlParameter("@FathersProfession", SqlDbType.NVarChar, 25); param[12] = new SqlParameter("@MothersName", SqlDbType.NVarChar, 50); param[13] = new SqlParameter("@MothersProfession", SqlDbType.NVarChar, 25); param[14] = new SqlParameter("@Age", SqlDbType.Int); param[15] = new SqlParameter("@Year", SqlDbType.NVarChar, 10); param[0].Value = GrNo; param[1].Value = Name; param[2].Value = DOB; param[3].Value = Std; param[4].Value = Div; param[5].Value = RollNo; param[6].Value = Sex; param[7].Value = MobileNo; param[8].Value = Address; param[9].Value = TelNo; param[10].Value = FathersName; param[11].Value = FathersProfession; param[12].Value = MothersName; param[13].Value = MothersProfession; param[14].Value = Age; param[15].Value = Year; for (int i = 0; i < param.Length; i++) { cmd.Parameters.Add(param[i]); } cmd.CommandType = CommandType.Text; cmd.ExecuteNonQuery(); } catch (System.Data.SqlClient.SqlException ex) { string msg = "Insert Error:"; msg += ex.Message; throw new Exception(msg); } finally { conn.Close(); } } private void button1_Click(object sender, EventArgs e) { ExecuteInsert(textBox1.Text, textBox2.Text, dateTimePicker1.Text,textBox4.Text,/*textBox4.Text*/ textBox5.Text, textBox6.Text, textBox7.Text, textBox8.Text, textBox9.Text, textBox10.Text, textBox11.Text, textBox12.Text, textBox13.Text, textBox14.Text, textBox15.Text,textBox16.Text); MessageBox.Show("Record was successfully added!"); ClearTextBoxes(this); label18.Visible = false; label19.Text = ""; label20.Text = ""; break; }
param[5] = new SqlParameter("@RollNo", SqlDbType.Int);
Here when i enter a value , it gives an error message «Index was outside the bounds of the array c#»
please help what should i do..
Answers
-
Hi, since you add 16 parameters, you should resize your array to:
SqlParameter[] param = new SqlParameter[15];
Mitja
-
Proposed as answer by
Monday, August 27, 2012 7:14 PM
-
Marked as answer by
Harshal Mehta
Thursday, August 30, 2012 4:12 PM
-
Proposed as answer by
-
It should be 16 since your array starts with 0.
SqlParameter[] param =
new SqlParameter[16];
jdweng
-
Proposed as answer by
Rajeev Harbola
Tuesday, August 28, 2012 11:19 AM -
Marked as answer by
Jason Dot WangModerator
Tuesday, September 4, 2012 8:40 AM
-
Proposed as answer by
-
It should be 16 since your array starts with 0.
SqlParameter[] param =
new SqlParameter[16]
Wrong. For that reason should be 15. As you say he have 16 params, starting with 0. When he reach param[15], he will reach all the 16 parameters.
Web Developer
-
Proposed as answer by
Akayster
Monday, August 27, 2012 7:52 PM -
Marked as answer by
Jason Dot WangModerator
Tuesday, September 4, 2012 8:40 AM
-
Proposed as answer by
-
Oh for Heaven’s sake!
Mitja made an obvious typo. Harshal’s code calls for 16 elements, numbered 0 to 15. Therefore he needs to declare his array as having 16 elements, just as Joel said.
If the array is declared like this…
SqlParameter[] param =
new SqlParameter[15];…then when he tries to do this…
param[15] = new SqlParameter("@Year", SqlDbType.NVarChar, 10);
…there will be a crash.
-
Edited by
Ante Meridian
Tuesday, August 28, 2012 12:23 AM -
Proposed as answer by
DanyR_
Tuesday, August 28, 2012 5:19 PM -
Marked as answer by
Jason Dot WangModerator
Tuesday, September 4, 2012 8:40 AM
-
Edited by
-
Hey Harshal Mehta:)
Another easy way is using AddWithValue!
private void ExecuteInsert(string
GrNo, string
Name, string DOB,
string Std,
string Div, string
RollNo, string
Sex, string MobileNo,
string Address,
string TelNo, string
FathersName, string
FathersProfession, string
MothersName, string
MothersProfession, string
Age, string
Year)
{
SqlConnection conn
= new SqlConnection(«Data Source =.;Initial Catalog=SAHS;User id=sa;password=faculty»);
string sql
= «INSERT INTO dbo.Student_Details (GrNo,Name,DOB,Std,Div,RollNo,Sex,MobileNo,Address,TelNo,FathersName,FathersProfession,MothersName,MothersProfession,Age,Year) VALUES «
+ » (@GrNo,@Name,@DOB,@Std,@Div,@RollNo,@Sex,@MobileNo,@Address,@……)
SqlCommand cmd = new SqlCommand(sql,conn);
cmd.Parameters.AddWithValue(«@YourParameter’s name»,»Your Real Value»);
……………………………………
}
下载MSDN桌面工具(Vista,Win7)
我的博客园
慈善点击,点击此处-
Proposed as answer by
Jason Dot WangModerator
Wednesday, August 29, 2012 7:51 AM -
Marked as answer by
Jason Dot WangModerator
Tuesday, September 4, 2012 8:40 AM
-
Proposed as answer by
In this article, we are going to learn about one of the most common exceptions in C# – IndexOutOfRangeException.
To download the source code for this article, you can visit our GitHub repository.
We’re going to learn about various situations where this exception gets raised and about the preventive measures we can take to make our applications more robust.
IndexOutOfRangeException
gets thrown when we try to access a member of an array or a collection using an invalid index.
An invalid index means either the index is lower than the collection’s lower bound or greater than/equal to the number of elements in the collection.
We are going to cover some common examples of where IndexOutOfRangeException
is raised.
Another exception you’re familiar with is NullReferenceException
. If you want to learn more, we have an article about NullReferenceException as well.
Array – Upper Bound
The upper bound of a zero-based array – should be one less than the array length.
Let’s create an integer array and run a for loop on it to demonstrate the exception:
var numbersArray = new int[] { 1, 2, 3, 4, 5 }; for (var i = 0; i <= numbersArray.Length; i++) { Console.WriteLine(numbersArray[i]); }
The for loop runs perfectly fine when i < 5
, but it fails for i == 5
because there is no element at the position 6 (index 5 – {0, 1, 2, 3, 4 , 5}):
1 2 3 4 5 Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
How to Fix IndexOutOfRangeException?
Now, let’s see how we can fix IndexOutOfRangeException
in this case.
Let’s remove the equality condition and just check for i < numbersArray.Length
:
var numbersArray = new int[] { 1, 2, 3, 4, 5 }; for (var i = 0; i < numbersArray.Length; i++) { Console.WriteLine(numbersArray[i]); }
And if we run the application again, there’s no exception this time:
1 2 3 4 5
Array – Custom Lower Bound
We can create an array with a custom lower bound by using the Array.CreateInstance(Type elementType, int[] lengths, int[] lowerBounds)
method:
var customLowerBoundArray = Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 1 }); var value = 2; for (var i = 0; i < customLowerBoundArray.Length; i++) { customLowerBoundArray.SetValue(value, i); value *= 5; }
The code snippet throws IndexOutOfRangeException
when we try to set the array element’s value at an index lower than the custom lower bound.
The lower bound is 1, but the first element is set at position 0 (i == 0
).
Solution
Let’s see how we can prevent the exception in this case:
var customLowerBoundArray = Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 1 }); var value = 2; for (var i = customLowerBoundArray.GetLowerBound(0); i <= customLowerBoundArray.GetUpperBound(0); i++) { customLowerBoundArray.SetValue(value, i); value *= 5; } for (var i = customLowerBoundArray.GetLowerBound(0); i <= customLowerBoundArray.GetUpperBound(0); i++) { Console.WriteLine(customLowerBoundArray.GetValue(i)); }
We make use of Array.GetLowerBound()
and Array.GetUpperBound()
methods to determine the start and end index of the custom lower bound array:
2 10 50 250 1250
List – Incorrect Arguments
This scenario is a little bit different:
Console.WriteLine("Please enter a search argument: "); var searchArg = Convert.ToInt32(Console.ReadLine()); var multiplesOfFive = new List<int> { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 }; Console.WriteLine($"Let's display the multiples of 5 greater than {searchArg}"); var startIndex = multiplesOfFive.IndexOf(searchArg); for (var i = startIndex; i < multiplesOfFive.Count; i++) { Console.WriteLine(multiplesOfFive[i]); }
We have a List<int>
to which we add the first 10 multiples of 5.
We take input from the user – searchArg
, and use this input to display numbers greater than the input.
An input other than the numbers present in the list results in an index of -1, which raises the ArgumentOutOfRangeException
.
An input of 12 breaks the code and we get the exception:
Please enter a search argument: 12 Let's display the even numbers greater than 12 Unhandled exception. System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Solution
To prevent the exception, we can add a check:
Console.WriteLine("Please enter a search argument!!!"); var searchArg = Convert.ToInt32(Console.ReadLine()); var multiplesOfFive = new List<int> { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 }; var startIndex = multiplesOfFive.IndexOf(searchArg); if (startIndex < 0) { Console.WriteLine($"The number {searchArg} does not exist in the list."); } else { Console.WriteLine($"Let's display the even numbers greater than {searchArg}"); for (var i = startIndex; i < multiplesOfFive.Count; i++) { Console.WriteLine(multiplesOfFive[i]); } }
An incorrect input (other than the numbers in the list) results in a user-friendly message:
Please enter a search argument: 22 The number 22 does not exist in the list.
IndexOutOfRangeException vs ArgumentOutOfRangeException
Lists raise ArgumentOutOfRangeException
when an item is accessed at an invalid index, whereas arrays raise IndexOutOfRangeException
for the same behavior:
IList<string> tempList = new string[] { "0" }; var foo = tempList[-1]; //ArgumentOutOfRangeException string[] tempArray = new string[] { "0" }; var bar = tempArray[-1]; //IndexOutOfRangeException
Two Arrays – Different Lengths
The IndexOutOfRangeException
is raised when we attempt to assign an array element to a different array that has fewer elements than the first array:
var array1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var array2 = new int[7]; array2[array1.Length - 1] = array1[array1.Length - 1];
The array1
length is 10, while the array2
length is 7.
We are trying to assign the last element of array1
to array2
, but since array2
is smaller (length is 7), we get the IndexOutOfRangeException
.
Solution
Now, let’s see how we can prevent the exception:
var array1 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var array2 = new int[array1.Length]; array2[array1.Length - 1] = array1[array1.Length - 1]; Console.WriteLine($"The last element of array2 is: {array2[array2.Length - 1]}");
We initialize the second array as similar to the first array’s length:
The last element of array2 is: 10
Getting Confused Between an Index and the Value of That Index
Let’s see this case with an example:
var oddNumbersArray = new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 }; foreach (var number in oddNumbersArray) { Console.WriteLine($"The odd number is: {oddNumbersArray[number]}"); }
We have an array of odd numbers, we run a foreach loop on the array and try to access the element using the index and not the element itself.
We start encountering IndexOutOfRangeException
when the number == 11
acts as the index.
There is no element at the 11th index:
The odd number is: 3 The odd number is: 7 The odd number is: 11 The odd number is: 15 The odd number is: 19 Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
Solution
We can prevent the exception easily by using the value itself, instead of trying to access the value by index in each iteration:
var oddNumbersArray = new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 }; foreach (var number in oddNumbersArray) { Console.WriteLine($"The odd number is: {number}"); }
This effectively prevents the exception:
The odd number is: 1 The odd number is: 3 The odd number is: 5 The odd number is: 7 The odd number is: 9 The odd number is: 11 The odd number is: 13 The odd number is: 15 The odd number is: 17 The odd number is: 19
DataTable – Incorrect Column Index
We create a method to render a static DataTable in a separate StaticDataRepository
class:
public class StaticDataRepository { public static DataTable GetGroceries() { var dataTable = new DataTable { TableName = "Groceries" }; dataTable.Columns.Add("Id", typeof(int)); dataTable.Columns.Add("Name", typeof(string)); dataTable.Columns.Add("Description", typeof(string)); dataTable.Rows.Add(1, "Macaroni", "Tasty Pasta"); dataTable.Rows.Add(2, "Ramen", "Tasty Noodles"); dataTable.Rows.Add(3, "Figaro Oil", "Olive Oil"); dataTable.Rows.Add(4, "XYZ Lentils", "Nutritious Pulses"); return dataTable; } }
We then run a foreach loop on the data table and try to access all the rows:
var groceries = StaticDataRepository.GetGroceries(); for (var i = 0; i < groceries.Rows.Count; i++) { var row = groceries.Rows[i]; Console.WriteLine($"{row[0]}t {row[1]}t {row[2]}t {row[3]}"); }
The code raises an IndexOutOfRangeException
because we are trying to access the 4th column (row[3]
), which is not present in the data table:
Unhandled exception. System.IndexOutOfRangeException: Cannot find column 3.
It is quite possible that we might not be aware of the number of columns in the incoming data table.
We may try to access a column that does not exist and encounter the exception.
Solution
Let’s see how we can prevent the exception in this scenario:
var groceries = StaticDataRepository.GetGroceries(); foreach (DataRow grocery in groceries.Rows) { foreach (var item in grocery.ItemArray) { Console.WriteLine($"{item}"); } Console.WriteLine("********************"); }
We do not hardcode the indexes, rather we make use of the inbuilt properties such as ItemArray
that is an array of objects:
1 Macaroni Tasty Pasta ******************** 2 Ramen Tasty Noodles ******************** 3 Figaro Oil Olive Oil ******************** 4 XYZ Lentils Nutritious Pulses ********************
These were the most common situations where we can stumble upon the IndexOutOfRangeException
.
Conclusion
We have learned about IndexOutOfRangeException in detail, the various scenarios where the exception gets raised, and the possible solutions.
Очень часто при работе с массивами или коллекциями можно столкнуться с исключением: Index was out of range. В чём заключается суть ошибки.
Представьте, что у Вас есть массив, состоящий из двух элементов, например:
int [] ar = new int [] {5,7};
Особенность массивов в языке c# заключается в том, что начальный индекс элемента всегда равен нулю. То есть в данном примере, не смотря на то, что число пять — это первое значение элемента массива, при обращении к нему потребуется указать индекс ноль. Так же и для числа семь, несмотря на то, что это число является вторым элементом массива, его индекс так же будет на единицу меньше, то есть, равен одному.
Обращение к элементам массива:
int a = ar[0]; int b = ar[1];
Результат: a = 5 и b = 7.
Но, стоит только указать неверный индекс, например:
int a = ar[2];
В результате получаем исключение: Index was outside the bounds of the array, то есть индекс находиться за границами диапазона, который в данном примере составляет от 0 до 1. Поэтому при возникновении данной ошибки, первое, что нужно сделать, так это убедиться в том, что Вы указали правильный индекс при обращении к элементу массива или обобщённой коллекции.
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team