Today we will discuss about One-Dimensional Arrays and and how we can use arrays with ASP.NET. Arrays are basically lists of sequentially accessible data. They provide a means of accessing and storing data in a way that allows multiple related elements to be manipulated via numeric index.
SampleArray.aspx
<form id=”form1″ runat=”server”>
<div>
<asp:Label ID=”Label1″ runat=”server” Width=”306px”></asp:Label><br />
<asp:DropDownList ID=”DropDownList1″ runat=”server” Width=”306px”>
</asp:DropDownList><br />
<asp:DropDownList ID=”DropDownList2″ runat=”server” Width=”306px”>
</asp:DropDownList> <br />
<asp:Label ID=”Label2″ runat=”server” Width=”306px”></asp:Label><br />
<asp:DropDownList ID=”DropDownList3″ runat=”server” Width=”306px”>
</asp:DropDownList><br />
<asp:Label ID=”Label3″ runat=”server” Width=”306px”></asp:Label><br />
<asp:Label ID=”Label4″ runat=”server” Width=”306px”></asp:Label></div></form>
SampleArray.aspx.cs
namespace WebApplication1
{
public partial class SampleArray : System.Web.UI.Page
{
//Declaring and Initializing Arrays
static private string[] names = new string[6] { “Paul”, “Harpreet”, “John”, “Andy”, “Jeff”, “Mike” };
static private string[] productNames = { “Blue Shirt”, “Red Shirt”, “Blue Pent”, “Red Pent” };
protected void Page_Load(object sender, EventArgs e)
{
foreach (string name in names)
{
//Show array items on lable
Label1.Text += (name) + “<br>”;
//populate Dropdownlist with array
DropDownList1.Items.Add(name);
}
//Sort array reversely
Array.Reverse(names);
foreach (string strReverseArray in names)
{
DropDownList2.Items.Add(strReverseArray);
}
// Find array element by array index
Label2.Text = names.GetValue(3).ToString();
//Sort the array
Array.Sort(names);
foreach (string strSort in names)
{
DropDownList3.Items.Add(strSort);
}
//Pass array as a parameter
showNames(names);
//use FindAll to search element
string[] blueProducts = Array.FindAll(productNames, IsBlueProduct);
foreach (string product in blueProducts)
{
Label4.Text += (product) + “<br>”;
}
}
private void showNames(string[] names)
{
int counter = 1;
foreach (string personName in names)
{
Label3.Text += counter+“. “+ (personName) + “<br>”;
}
counter++;
}
static bool IsBlueProduct(string productName)
{
if (productName.ToUpper().Contains(“BLUE”))
return true;
else
return false;
}
}
}
- Harpreet Virk
Posted by hsvirk