We help IT Professionals succeed at work.

# How to change the length of the array at run time.

on
Medium Priority
631 Views
I have an array of datarows. I have couple of questions here:

1. Is is necessary to assign the length of the array at the design time? Can we not set it at run time.

2. Lets suppose we have set the length of the array at the design time. This needs to be changed at run time depends upon the number of elements filled in the array. Can we do that.

Please see the code attached. I have an array of datarows. I have given assigned it the length of 10 at design time. This I assume I had to because if I was leaving it blank it was giving me error saying 'Index is out of boud'. At run time I fill this array with few rows. lets suppose 2 rows. Now the initial length declared was 10 and it contains only 2 elements. How can I change the length of the array.
``````DataRow[] rowsToDel = new DataRow[10];

int totCols = ds.Tables[0].Columns.Count;
int totRows = ds.Tables[0].Rows.Count;

int rowDelCnt = 0;

foreach (DataRow dR in ds.Tables[0].Rows )
{
Boolean isDel = (Boolean) dR[totCols-1];
if (isDel)
{
rowsToDel[rowDelCnt] = dR;
rowDelCnt++;
}
}
``````
Comment
Watch Question

## View Solution Only

Commented:
You can say
DataRow[] rowsToDel = new DataRow[ds.Tables[0].Rows.Count];
I think count is there off the top of my head

Commented:
oops sorry just realised you only want certain rows!
However you can see that yews it can be set at design time  - you just need different code to mine that's all.
Note also that you can use ArrayList

Commented:
Sorry excuse my typing meant to say yes it can be set at run time (not design time)
Software Engineer
CERTIFIED EXPERT

Commented:

Commented:
do I need to assign the length before I fill in the elements or after.

Commented:
for an array before
for an ArrayList you don't you just add them ad hoc
Commented:
I have found the right solution of it. Please see the function below

Array.Resize(ref "arrayName", "Newsize")
Array.Resize(ref rowsToDel, rowDelCnt)

Thanks for all of your help

Not the solution you were looking for? Getting a personalized solution is easy.

Technical SEO Consultant

Commented:
I would not say thats the simplest or best way.

in 1.1 use an ArrayList

otherwise I'd use generics and List<DataRow>

``````List<DataRow> rowsToDel = new List<DataRow>();

int totCols = ds.Tables[0].Columns.Count;
int totRows = ds.Tables[0].Rows.Count;

int rowDelCnt = 0;

foreach (DataRow dR in ds.Tables[0].Rows )
{
Boolean isDel = (Boolean) dR[totCols-1];
if (isDel)
{
}
}
``````
Access more of Experts Exchange with a free account
##### Thanks for using Experts Exchange.

Limited access with a free account allows you to:

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile