0

I have membership database which contains Roles defined in the role table..Now i want to make datatable to be created dynamically from the the number of roles present in roles table...

here is my code..

DataTable dTable = new DataTable();

string[] rolesarr = Roles.GetAllRoles();
int length = rolesarr.Count();

for (int i = 0; i <= length; i++)
{
     string colname = rolesarr[i];
     if (i == 0)
     {
         dTable.Columns.Add(colname, typeof(string));
     }
     else
     {
         dTable.Columns.Add(colname, typeof(bool));
     }
}

but it is giving error as

"System.IndexOutOfRangeException: Index was outside the bounds of the array."

Any help will be highly appreciated. Thanks in advance..

0

1 Answer 1

4

Change your

i <= length

to

i < length

Because arrays are zero based. Their bounds are 0 to length - 1.

From Arrays (C# Programming Guide)

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

For example, when you declare an array with 5 elements like;

int[] array = new int[5];

Your elements as indexed from 0 to 4 like;

array[0]
array[1]
array[2]
array[3]
array[4]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.