ASP.Net C# Add to String Array using for loop

Updated on 17 May 2012,
Published on 04 Jul 2008

You can use for loop in ASP.Net C# to add items to string array. Topic of basic array collection is considered as outdated today but sometimes for better server memory management using low memory consuming objects string array is used in ASP.Net web pages. This tutorial has been compiled only for beginner level developers to learn the use of C# for loop to add items to string array dynamically at each index of array collection. Latter on, in the series of ASP.Net C# tutorials of programming ezine of we will discuss about advanced features of Generic collections introduced in ASP.Net 2.0 and later versions.

Basically, while using string type array in C# ASP.Net you can declare the instance of array by passing the integer type variable as the length of the array. E.g.:

int arrLength = 10;

string[] arr1 = new string[arrLength];

At next level you can add items to string array declared above using for loop as given below:

int i = 0;

for (i = 0; i < arr1.Length; i++)
    arr1[i] = "index " + i;

In the above C# sample code for loop contains the test condition "i < arr1.Length", it checks whether the incremented value of "i" is less than the maximum length of the declared array. If the test condition returns false then it exits for loop. Inside the for loop code block each index of arr1 is assigned a value. You can use the same method while using the string array in real time projects.

You can also use the for loop in ASP.Net C# to read the values at each index of array as follows:

for (i = 0; i < arr1.Length; i++)
    Response.Write(arr1[i] + "<br />");

index 0
index 1
index 2
index 3
index 4
index 5
index 6
index 7
index 8
index 9

Continue to next tutorial: ASP.Net Loop through Array Using C# for Loop to learn about the user of for loop over the collection to read the items.

3 Responses to "ASP.Net C# Add to String Array using for loop"
i have one text box and one insert button. In that text box i have to insert strings.
it is not limited. it will be maintained in array or stored in array.

another one is dropdown list is there. in that ascending and descending is there. if we select descending means the stored strings are displayed in descending order. otherwise it will be displayed in ascending order.

thanks for good examples
This is a great inspiring article. I am pretty much pleased with your good work. You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post.
Leave a Comment
* required
* required
* will not be published
* optional
* hint:
  • Subscribe via Email