Sunday, November 15, 2009

Convert DataSet into ArrayList in C#

Converting the DataSet into ArrayList is not an big deal anymore.
If you are sure about the number of columns in the DataTable,create the same class members in the Class.

Let assume I have an DataSet contains of the table named "Product" which has three columns called ProductID and Stock.

First step to convert the DataSet into ArrayList is,creating the Class name ProductClass



Database db = DatabaseFactory.CreateDatabase("DatabaseConnectionString");
DbCommand cmd = db.GetSqlStringCommand("Select * from Products");
DataSet ds = db.ExecuteDataSet(cmd);
List proList = new List();

for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Products p = new Products();
p.ProductName = ds.Tables[0].Rows[i]["ProductName"].ToString();
p.ProductID = ds.Tables[0].Rows[i]["ProductID"].ToString();
proList.Add(p);

}


Product.cs

public class Products
{
private string _productName;

private string _productid;

public string ProductName
{
get { return _productName; }
set { _productName = value; }


}

public string ProductID
{
get { return _productid; }
set { _productid = value; }

}



}

GridView1.DataSource = proList.ToArray();
GridView1.DataBind();