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..
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.