Link to home
Start Free TrialLog in
Avatar of shieldguy
shieldguyFlag for United Kingdom of Great Britain and Northern Ireland

asked on

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

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++;
                }
            }

Open in new window

Avatar of daveamour
daveamour
Flag of United Kingdom of Great Britain and Northern Ireland image

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

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
Sorry excuse my typing meant to say yes it can be set at run time (not design time)
Avatar of masheik
Avatar of shieldguy

ASKER

do I need to assign the length before I fill in the elements or after.
for an array before
for an ArrayList you don't you just add them ad hoc
ASKER CERTIFIED SOLUTION
Avatar of shieldguy
shieldguy
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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)
	{
		rowsToDel.Add(dR);
	}
}

Open in new window