Infolink

 

Search This Blog

Nov 30, 2012

ArrayList in Asp.net

The ArrayList object is a collection of items containing a single data value.

Items are added to the ArrayList with the Add() method.

The following code creates a new ArrayList object named books and three items are added:
  ArrayList books = new ArrayList();
  books.Add(”book1");
  books.Add(”book2");
  books.Add(”book3");


By default, an ArrayList object contains 16 entries. An ArrayList can be sized to its final size with the TrimToSize() method:
  books.TrimToSize();
An ArrayList can also be sorted alphabetically or numerically with the Sort() method:
  books.Sort();

To sort in reverse order, apply the Reverse() method after the Sort() method:
  books.Sort();
  books.Reverse();
Data Binding to an ArrayList

An ArrayList object may automatically generate the text and values to the following controls:

asp:RadioButtonList
asp:CheckBoxList
asp:DropDownList
asp:Listbox
To bind data to a RadioButtonList control, first create a RadioButtonList control (without any asp:ListItem elements) in an .aspx page:
<html>
<body><form runat=”server”>
<asp:RadioButtonList id=”rb” runat=”server” />
</form></body>
</html>
Then add the code that builds the list and binds the values in the list to the RadioButtonList control in the code behind:
protected void Page_Load(object sender, EventArgs e)
{
  ArrayList books = new ArrayList();
  books.Add(”book1")
  books.Add(”book2")
  books.Add(”book3")
  books.TrimToSize()
  books.Sort()
  rb.DataSource=books
  rb.DataBind()
}
The DataSource property of the RadioButtonList control is set to the ArrayList and it defines the data source of the RadioButtonList control. The DataBind() method of the RadioButtonList control binds the data source with the RadioButtonList control.

Note: The data values are used as both the Text and Value properties for the control. To add Values that are different from the Text, use either the Hashtable object or the SortedList object.

Converting HashTable into ArrayList and binding to DataControls

Following code snippet shows how to convert HashTable into ArrayList and Bind to DataControls.
Class MyClass

{

public static ArrayList HashTableToArrayList(Hashtable hTable)

        {

            ArrayList list = new ArrayList();

            foreach (int key in hTable.Keys)

            {

                list.Add(hTable[key]);

            }

            return list;

        }

}
Now you can use above function to Bind any DataControls like GridView.
GridView1.DataSource = MyClass.HashTableToArrayList(myhashTable);

GridView1.DataBind();

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...