SIGN UP MEMBER LOGIN:    
ARTICLE

Binding an ArrayList with DataGrid Control

Posted by Mahesh Chand Articles | Visual C# October 24, 2005
I have seen several questions on how to bind an ArrayList with data-bound controls such as a DataGrid. In this step by step tutorial, I will show how to create an ArrayList of objects and bind it to a DataGrid control.
Reader Level:
Download Files:
 

In this article, I will discuss how to create an ArrayList of objects and bind it to a DataGrid control using DataSource property.

Step 1. Creating a Class

First step is to create a class. I call my class Developer, which is listed in Listing 1. It's properties are FirstName, LastName, Age, Skills, and Experience.

public class Developer
{
      private string firstName; 
      private string lastName;
      private int age;
      private string skills; 
      private int experience; 
      public Developer(string firstName, string lastName, int age, string skills, int experience ) 
      {
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
            this.skills = skills;
            this.experience = experience;
      }
      /// <summary>
      /// First Name
      /// </summary>
      public string FirstName
      {
            get { return this.firstName ; }
      }
      /// <summary>
      /// Last Name
      /// </summary>
      public string LastName
      {
            get { return this.lastName ; }
      }
      /// <summary>
      /// Age 
      /// </summary>
      public int Age
      {
            get { return this.age ; }
      }
      /// <summary>
      /// Skill set
      /// </summary>
      public string Skills
      {
            get { return this.skills ; }
      }
      /// <summary>
      /// Number of year experience
      /// </summary>
      public int Experience
      {
            get { return this.experience ; }
      }
}

Listing 1. Developer class

Step 2. Creating an ArrayList of Objects

Now next step is to create an ArrayList object of Developer class. Listing 2 adds 6 items to the ArrayList.

private ArrayList GetList()
{
      ArrayList list = new ArrayList();
      list.Add(new Developer("Mahesh", "Chand", 30, "C#,ASP.NET,Windows Forms", 10)) ; 
      list.Add(new Developer("Michael", "Gold", 35, "GDI+, ASP.NET", 15)) ; 
      list.Add(new Developer("Bhasker", "Das", 26, "VB.NET, Web Applications", 4)) ; 
      list.Add(new Developer("Ashish", "Singhal", 24, "ADO.NET, GDI+", 4)) ; 
      list.Add(new Developer("Neel", "Beniwal", 3, "C#,ASP.NET,Windows Forms", 0)) ;
     
list.Add(new Developer("Melanie", "Talmadge", 25, "Java", 2)) ; 
      return list;
}

Listing 2. ArrayList of Developer  

Step 3. Binding with DataGrid

Now we can bind our ArrayList using DataGrid.DataSource property and DataGrid would understand what to display in its columns. The following code binds the ArrayList to DataGrid.

ArrayList list = GetList();

dataGrid1.DataSource = list;

Step 4. The Result

Now if I run my application, the output in DataGrid looks like Figure 1.

ArrayListImg1.gif

Figure 1. Developers in a DataGrid

Step 5. Formatting DataGrid Columns

As you can see from Figure 1, the column names of the DataGrid are same as property names of the Developer class. Now many developers asked me questions, how to change the column header and the size of headers.

To do this, we need to take helo of DataGridTableStyle and DataGridColumnStyles. A DataGridTableStyle object represents the style of the entire DataGrid. In Listing 3, I create a new DataGridTableStyle and later I create ColumnStyles and add ColumnStyles to the TableStyles. In the end of the code, I remove the current TableStyle of the DataGrid and add new style.

// Create a Custom TableStyle

DataGridTableStyle tableStyle = new DataGridTableStyle();

tableStyle.MappingName = "ArrayList";

tableStyle.HeaderFont = new Font("Verdana", 9, FontStyle.Bold);

tableStyle.HeaderForeColor = Color.OrangeRed;

int colwidth = (dataGrid1.ClientSize.Width - tableStyle.RowHeaderWidth

      - SystemInformation.VerticalScrollBarWidth) / 6;                 

// Create a DataGridColumn, set its header text and other properties

DataGridTextBoxColumn cs = new DataGridTextBoxColumn();

cs.MappingName = "FirstName"; 

cs.HeaderText = "First Name";

cs.Width = colwidth;

// Add Column to GridColumnStyles

tableStyle.GridColumnStyles.Add(cs); 

// Create a DataGridColumn, set its header text and other properties

cs = new DataGridTextBoxColumn();

cs.MappingName = "LastName"; 

cs.HeaderText = "Last Name";

cs.Width = colwidth;

// Add Column to GridColumnStyles

tableStyle.GridColumnStyles.Add(cs); 

// Create a DataGridColumn, set its header text and other properties

cs = new DataGridTextBoxColumn();

cs.MappingName = "Age"; 

cs.HeaderText = "Age";

cs.Width = colwidth;

// Add Column to GridColumnStyles

tableStyle.GridColumnStyles.Add(cs);                 

// Create a DataGridColumn, set its header text and other properties

cs = new DataGridTextBoxColumn();

cs.MappingName = "Experience"; 

cs.HeaderText = "Exp (Years)";

cs.Width = colwidth;

// Add Column to GridColumnStyles

tableStyle.GridColumnStyles.Add(cs); 

// Create a DataGridColumn, set its header text and other properties

cs = new DataGridTextBoxColumn();

cs.MappingName = "Skills"; 

cs.HeaderText = "Skills";

cs.Width = colwidth + colwidth;

// Add Column to GridColumnStyles

tableStyle.GridColumnStyles.Add(cs); 

// Get rid of current table style

dataGrid1.TableStyles.Clear();

// Add new table style to the Grid

dataGrid1.TableStyles.Add(tableStyle);

Listing 3. Formatting a DataGrid

As you can see from Listing 3, I create a DataGridTextBoxColumn, set its MappingName to name of the property of Developer class, Header Text to the text I want to display on the header, and Width to the width of the column. After that I add  DataGridTextBoxColumn to TableStyle.

Now new formatted DataGrid looks like Figure 2.

ArrayListImg2.gif

Figure 2. Formatted Developers in a DataGrid

Summary

In this step by step tutorial, I discussed how to create an ArrayList of objects and bind it to a DataGrid control. After that I also discussed how to format the DataGrid columns to suite the style of the data.  Download the attached source code and run it. You will find some other good stuff in the source code ;-).

Login to add your contents and source code to this article
share this article :
post comment
 

How to Format DataGrid Columns in ASP.NET when using arraylist as mentioned in your article as DataGridTableStyle is not available in ASP.NET

Posted by smitdso Feb 09, 2007

do u know the coding for how to retrieve values from a access database.for egif i want to retrieve values like first name,lastname in an order in a datagrid.

Posted by prasanth k Jan 22, 2007

 Hi

Please this is urgent. I looked at your article it looks great. How about if I wanted to add an edit button column to the datagrid. once the datagrid is bound to the array list it seems impossible to add any columns to it neither thru the designer nor thru the code. Any helpful hints?

 

thanks

Posted by Naji sResume Nov 25, 2006

Why you want to divide data from DB? Isn't be better tj hide bouded column with PersonID?

Posted by matt cooper Feb 27, 2006

You may want to post this question on forums or look at Windows Forms controls ection for the sample code. These questions are related to the above article only.

Cheers!
Mahesh

Posted by Mahesh Chand Jan 04, 2006
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Nevron Gauge for SharePoint
Become a Sponsor