Saturday, December 10, 2011

Reading DataRow into Generic class

Recently I worked out for an business requirement to split the number of rows as per the value.
Example if a purchase order contains number of quantity as 5.Then my code should create the 5 records on the same purchase order and splitting the quantities as 1.
Here is an XML file:



  
    004
    Samsung Galaxy Tab
    1
      
  
  005
  iPhone
  1
  
  
    006
    Nokia
    2
  

  
    007
    Motorola Razer Tab
    5
  
  
Here I read these records into generic class and identifying the each product's quantity.So there will be 9 record generated. Always best practice to read the Data Row in to generic class.
public class ExcelColumns
{
 public ExcelColumns(string PID,string PName,int PQN)
 {
        this.ProductID = PID;
        this.ProductName = PName;
        this.Quantity = PQN;
 }

    private string pId, pName;
    private int quantity;
    public string ProductID
    {
        get { return pId; }
        set { pId = value; }

    }

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

    public int Quantity
    {
        get { return quantity; }
        set { quantity = value; }

    }

}
Reading the each row and applying the logic here
      DataSet ds = new DataSet();

        ds.ReadXml(@"D:\SPProjects\First\Products.xml");
        List list = new System.Collections.Generic.List();
        foreach (DataRow row in ds.Tables[0].Rows)
        {
            if (Convert.ToInt32(row[2]) == 1)
            {
                list.Add(new ExcelColumns(row[0].ToString(), row[1].ToString(), Convert.ToInt32(row[2])));
            }
            else
            {
                int a = Convert.ToInt32(row[2]);

                for (int b = 0; b < a; b++)
                {

                    list.Add(new ExcelColumns(row[0].ToString(), row[1].ToString(), 1));
                }

            }

        }

        GridView1.DataSource = list;
        GridView1.DataBind();