Monday, 24 June 2013

Concept of Datatable

   Datatable dtCommon ;

//Adding Columns to Datatable

            dtCommon .Columns.Add("Amount1");
            dtCommon .Columns.Add("Amount2");
            dtCommon .Columns.Add("Amount3");
            dtCommon .Columns.Add("Amount4");
            dtCommon .Columns.Add("Amount5");

//change the datatype of the column

        dtCommon .Columns[1].DataType = typeof(string);

//change the datatype of the column when  the datatable has some data


DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Int32);
foreach (DataRow row in dt.Rows) 
{
    dtCloned.ImportRow(row);
}
//copy one by one row to another datatable

  foreach (DataRow row in dt.Rows)
            {
                dtNew.ImportRow(row);
            }

//Assigning values to rows of datatable

             foreach (DataRow dr in dt.Rows)
            {
                dr["Amount1"] = "0.00";
                dr["Amount2"] = "0.00";
                dr["Amount3"] = "0.00";
                dr["Amount4"] = "0.00";
                dr["Amount5"] = "0.00";

            }
//Selecting records from Datatable

     DataRow[] drNewsContent = dtCommon .Select("Nid="+Convert.ToInt32(DataKey));

 //copy the structure of datatable

   DataTable newDatatable = OldDatatable.Clone();

//Filtering records from datatable based on groupby multiple columns
 
      dtCommon = dtCommon.DefaultView.ToTable(true, "Col1", "Col2", "Col3");

//Assigning Datarow to Datatable

DataRow[] drFilteredRecord = dtCommon.Select("SchoolId<>''");
if (drFilteredRecord.Length > 0)
 {
   DataTable dtFilteredRecord = drFilteredRecord.CopyToDataTable();
 }

//Assigning Datarow to Datatable (Another Way)

 DataRow[] UniqueSchoolClassSection = dt.Select("SchoolId<>''");
 if (UniqueSchoolClassSection.Length > 0)
  {
    foreach (DataRow dr in UniqueSchoolClassSection)
     {
       dtNew.ImportRow(dr);
     }
             
  } //Both datatable and Datarow Must have same structure    

Getting Distinct Records from datatable


dataTable.DefaultView.ToTable(true, "employeeid");
Where:
  • first parameter in ToTable() is a boolean which indicates whether you want distinct rows or not.
  • second option in the ToTable() is the column name based on which we have to select distinct rows

    Filtering records from datatable and store to another 

    DataView dv_Records=dtResult.DefaultView;           
                dv_Records.RowFilter="Session=" + Year + "";
                if (dv_Records.Count>0)
                {                
                    dtFilterRecords = dv_Records.ToTable();
                }          


    Agreegate Function on Datatable

    object Cashsum;
     Cashsum = dtRecords.Compute("sum(CurrentPaid)", "PaymentMode='Cash'");
    //2nd parameter is the condition

No comments:

Post a Comment