简体   繁体   English

在ASP.NET中创建动态数据表

[英]Dynamic DataTable Creation in ASP.NET

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." “ System.IndexOutOfRangeException:索引超出了数组的范围。”

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 . 它们的范围是0length - 1

From Arrays (C# Programming Guide) Arrays (C# Programming Guide)

Arrays are zero indexed: an array with n elements is indexed from 0 to n-1 . 数组的索引为零:具有n个元素的数组的索引从0n-1

For example, when you declare an array with 5 elements like; 例如,当您声明包含5个元素的数组时,例如;

int[] array = new int[5];

Your elements as indexed from 0 to 4 like; 您的元素从04索引;

array[0]
array[1]
array[2]
array[3]
array[4]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM