ASP.NET Basics (Part 5): Cooking Up a Storm - Changing Things Around
(Page 5 of 8 )
In order to modify an element of an array, you need to simply assign a new value to the corresponding variable. If you wanted to replace "chocolate fudge cake" with "chocolate chip cookies," you'd simply use
<%
desserts[3] = "chocolate chip cookies";
%>
and the array would now read
<%
string [] desserts = {"chocolate mousse", "tiramisu", "apple pie", "chocolate chip cookies", "caramel custard"}; %>
You can obtain the number of items in an array with the "Length" property (note the uppercase L), as demonstrated below:
<SCRIPT language=C# runat="server">
void Page_Load()
{
string [] desserts = {"chocolate mousse", "tiramisu", "apple pie", "chocolate fudge cake", "caramel custard"};
output.Text = "The dessert menu contains " + desserts.Length + " items."; }
</SCRIPT>
<asp:label id=output runat="server"></asp:label>
And the output is:
You can use a "for" loop to iterate through the elements of an array, as the following example demonstrates.
<SCRIPT language=C# runat="server">
void Page_Load()
{
// define counter
int counter;
string [] desserts = {"chocolate mousse", "tiramisu", "apple pie",
"chocolate fudge cake", "caramel custard"};
for (counter = 0; counter < desserts.Length; counter++)
{
output.Text = output.Text + "<li>" + desserts[counter] + "
";
}
}
</SCRIPT>
Desserts available:
<UL><asp:label id=output runat="server"></asp:label></UL>
And the output is as follows:
Next: A Full Meal >>
More ASP.NET Articles
More By Harish Kamath (c) Melonfire