Generics : An easy way to bind the data in DataGridView
Applied to: Visual Studio 2005 [C#]
Yes this is Generics. The concept which helps us to create collection easily and elegantly. Two steps to create the list is demonstrated here.
Step 1:
You have one object say for list of products which contains three properties Name, Quantity and Price.
using System;
using System.Collections.Generic;
using System.Text;
namespace MSDN_Generics
{
class Product
{
private int _Quantity;
public int Quantity
{
get { return _Quantity; }
set { _Quantity = value; }
}
private int _Price;
public int Price
{
get { return _Price; }
set { _Price = value; }
}
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
/// <summary>
/// Constructor to initialize the class
/// </summary>
/// <param name="sName"></param>
/// <param name="iQty"></param>
/// <param name="iPrice"></param>
public Product(string sName, int iQty, int iPrice)
{
_Name = sName;
_Quantity = iQty;
_Price = iPrice;
}
}
}
Step 2: Create a List of this class to use it for DataGridView’s datasource.
List<Product> myProds = new List<Product>();
myProds.Add(new Product("Prod 1", 1, 1));
myProds.Add(new Product("Prod 2", 2, 2));
myProds.Add(new Product("Prod 3", 3, 3));
myProds.Add(new Product("Prod 4", 4, 4));
myProds.Add(new Product("Prod 5", 5, 5));
myProds.Add(new Product("Prod 6", 6, 6));
myProds.Add(new Product("Prod 7", 7, 7));
dataGridView1.DataSource = myProds;
You need a namespace reference to use this Generic listing System.Collections.Generic