There are 102 guests and 0 members online. Who is online?

home  »  articles  »  C# DataGridView control with custom collection in Windows Forms

C# DataGridView control with custom collection in Windows Forms

change text size: A A A

Published on 3/22/2009 by vivek_iit

Introduction

Windows DataGridView control in .NET 2.0 and above supercedes the old DataGrid control. The DataGridView control provides many basic and advanced features that are missing in the DataGrid control. Also, it is easier to to extend and customize the DataGridView control than the DataGrid control.

Implementation Code

Here is a simple method on how to implement and use a basic DataGridView control in your windows applications. First create a simple Windows Forms Application in your VS 2008 IDE. Then on the default form (MyForm.cs), drag and drop a datagridview control and name it as dgridCustomers. We will be binding this grid with a Customer collection (custom generic collection).

To start with,assume that you have a customer class as:

public class Customer

{

    private int _customerID;
    private string _name;
    private DateTime _dob;  //date of birth
    private string _phoneNumber;

    public int CustomerID
    {
        get { return _customerID; }
        set { _customerID = value; }
     }

     public string Name
    {
        get { return _name; }
        set { _name= value; }
     }

     public DateTime DOB
    {
        get { return _dob; }
        set { _name= dob; }
     }

     public string PhoneNumber
    {
        get { return _phoneNumber; }
        set { _phoneNumber= value; }
     }

    //methods go here
}


Now create a method to set the number of columns and layout of the grid as follows (in the MyForm.cs class):

   private void SetGridLayout()
        {

           //clear any previously set columns
            dgridExample.Columns.Clear();           

            DataGridViewTextBoxColumn dgridColID = new DataGridViewTextBoxColumn();
            dgridColID .HeaderText = "ID";
            dgridColID .Name = "ColCustomerID";
            dgridColID .Width = 20;
            dgridColID .DataPropertyName = "CustomerID";
            dgridCustomers.Columns.Add(dgridColID );

            DataGridViewTextBoxColumn dgridColName = new DataGridViewTextBoxColumn();
            dgridColName .HeaderText = "Customer Name";
            dgridColName .Name = "ColName";
            dgridColName .Width = 200;
            dgridColName .DataPropertyName = "FullName";
            dgridCustomers.Columns.Add(dgridColName );

            DataGridViewTextBoxColumn dgridColDate = new DataGridViewTextBoxColumn();
            dgridColDate .HeaderText = "Date of Birth";
            dgridColDate.Name = "ColDate";
            dgridColDate.Width = 70;
            dgridColDate.DataPropertyName = "DateOfBirth";
            dgridCustomers.Columns.Add(dgridColDate);


            DataGridViewTextBoxColumn dgridColPhone = new DataGridViewTextBoxColumn();
            dgridColPhone .HeaderText = "Source Directory";
            dgridColPhone .Name = "ArchiveDirectory";
            dgridColPhone .Width = 100;
            dgridColPhone .DataPropertyName = "PhoneNumber";
            dgridCustomers.Columns.Add(dgridColPhone );
          
        }


Next we will bind this datagridview control with a list of Customer objects, as follows:


   private void BindCustomers()
        {

 

            //assume that we have a CustomerCollection class which is returning
           // a strongly typed list of all customers (a collection of Customer objects)
            CustomerCollection coll = new CustomerCollection()
            Collection<Customer> customers = coll.FindCustomers();
            if (customers.Count > 0)
            {           

                dgridCustomers.DataSource= customers;

            }         
        }

The above code simply binds our datagrid with the list of the objects returned. Now we will put the following code in the form's constructor so that we can set the autogeneratecolumns property to false and call the bind method.

public MyForm()
        {
            InitializeComponent();
           
            dgridCustomers.AutoGenerateColumns = false;           
            SetGridLayout();
           
            BindCustomers();
        }


We have set the AutoGenerateColumns property to false because we do not want the datagridview to add columns by itself based on the list of properties in the collection. Since we have already set the columns we want to show in the grid, we will disable the automatic columns generation.

So we have seen that using datagridview is really simple and easy, with the flexiblity of having our own custom layouts.

To rate this article please register or login

Author

vivek_iit vivek_iit (Member since:11/27/2008)
I am one of the administrators at CodeAsp.Net and I love programming, architecting solutions, code reviews, teaching and writing about ASP.NET.

Comments (3)

  • rowifi 8/31/2009 3:10:15 PM by:  rowifi
    ' //assume that we have a CustomerCollection class ... returning a strongly typed list .. ' As a novice - it would be infinitely useful to see how this is done here. Thanks!
  • rowifi 8/31/2009 3:08:16 PM by:  rowifi
    ' //assume that we have a CustomerCollection class ..... returning a strongly typed list ... ' It would be infinitely useful as a novice to see how we do this in this context .. as I don't know how!
  • 6/19/2009 11:39:21 AM by: 
    Gee thank you for that lovely piece of insight.... nobody cares

Post a comment

Comment  (No HTML)   

Type the characters:
 *
 

Related articles

Join CodeAsp.Net for FREE Today!

It's fast, easy and free! Submit articles, get your own blog, ask questions & give answers in the forums, and become a better developer, faster.

enter your email address:

Latest Articles RSS Feed

Latest articles

.
  • how to change Visual Studio's default browser
    12/15/2009
    how to change Visual Studio's default browser
  • Access dropdownlist inside the gridview
    12/10/2009
    Hi Friends, Many times we came cross the requirement when we need to access the dropdownlist's selectedindexchanged event inside the gridview, like in a shopping cart changing the item's quantity or binding the other dropdown based on the first dropdown.
  • JavaScript Expandable / Collapsible Panel Control
    12/4/2009
    This is the approach that I have adopted to develop Expandable / Collapsible Panel Control through JavaScript. Please report bugs, errors and suggestions to improve this control.
  • JavaScript ListBox Control
    12/3/2009
    This is my approach to develop custom JavaScript ListBox control. Although it is only a subset of existing HTML ListBox element, it is more user friendly than the existing one. It can be further customized for different requirements. Please let me know ab...
  • Multiple File Upload User Control
    11/27/2009
    I have tried my best to make this user control code error free. I will most welcome suggestions for further improvement in this user control. I have tested this user control on various browsers and it works fine.
  • Slide-Show User Control
    11/26/2009
    So, this is my approach to implement an ASP.NET slide show using the DataList. I have tried my best to keep it bug free. I will most welcome suggestions and criticism for further improvements of this user control. I have tested this user control on variou...
  • Implement: Paging in Repeater or Datalist Control
    11/18/2009
    As we all knows that Repeater and DataList does not have auto paging support technique like Gridview or Datagrid, but we can achieve this through PagedDataSource. By using PagedDataSource we can implement paging in Repeater or DataList. Now in our mind t...
  • JavaScript Context Menu Control
    11/6/2009
    So this is my approach. I was working for a long time to create C# like event handlers for JavaScript classes and finally, I’ve done it. Please let me know of any bugs and suggestions to improve this context menu control.
  • Maintaining States of Selected CheckBoxes in Different Pages inside the GridView
    11/4/2009
    So this is my solution. If you have some other ideas about this functionality, please share them with me.
  • GridView Rows Navigation Using Arrow (Up/Down) Keys
    11/4/2009
    I have tried my best to make this code error free. Suggestions and criticism for further improvements of this code are most welcome.

More Articles