Tags down


C#: retrieve the first n records from a DataTable

By : Hamish
Date : October 16 2020, 11:12 AM
I hope this helps . I have a DataTable that contains 2000 records. , If it implements IEnumerable:
code :

Share : facebook icon twitter icon

Looping through records from one DataTable and populating another DataTable in vb.net

By : Maaz
Date : March 29 2020, 07:55 AM
will be helpful for those in need you can copy DataTableA to DataTableB, add column and do business logic on each row, something like this:
code :
  DataTable dataTableB = dataTableA.Copy();
  dataTableB.Columns.Add("ProcessedValue", typeof(string));

  foreach (DataRow rw in dataTableB.Rows)
    rw.SetField<string>("ProcessedValue", BusinessLogic(rw.Field<int>("ProductID")));

how to compare 2 datatable and get unique records in 3rd datatable?

By : Weil Jimmer
Date : March 29 2020, 07:55 AM
I hope this helps you . I have 2 datatable let say dtData1 and dtData2. I have records in both the datatable I want to compare both the data table and want to create a new datatable let say dtData3 with uniqe records.
code :
public DataTable CompareTwoDataTable(DataTable dtOriginalTable, DataTable dtNewTable, ArrayList columnNames)
        DataTable filterTable = new DataTable();
        filterTable = dtNewTable.Copy();
        string filterCriterial;
        if (columnNames.Count > 0)
            for (int iNewTableRowCount = 0; iNewTableRowCount < dtNewTable.Rows.Count; iNewTableRowCount++)
                filterCriterial = string.Empty;
                foreach (string colName in columnNames.ToArray())
                    filterCriterial += colName.ToString() + "='" + dtNewTable.Rows[iNewTableRowCount][colName].ToString() + "' AND ";
                filterCriterial = filterCriterial.TrimEnd((" AND ").ToCharArray());
                DataRow[] dr = dtOriginalTable.Select(filterCriterial);
                if (dr.Length > 0)
        return filterTable;

trying to retrieve data from one datatable and i am trying to populate another datatable based on certain conditions usi

By : AmonGard
Date : March 29 2020, 07:55 AM
this will help I am using the code below. , Try code below
code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
    public partial class Form1 : Form
        public Form1()

            DataTable dta = new DataTable();
            dta.Columns.Add("Emp_Name", typeof(string));

            dta.Columns.Add("User_Shift", typeof(string));
            dta.Columns.Add("Shift_Emp_Status", typeof(string));
            dta.Columns.Add("Shift_Date", typeof(DateTime));
            dta.Columns["Shift_Date"].AllowDBNull = true;

            dta.Rows.Add(new object[] { "John", "Morning", "abc", DateTime.Parse("1/1/15") });
            dta.Rows.Add(new object[] { "John", "Morning", "abc", DateTime.Parse("1/2/15") });
            dta.Rows.Add(new object[] { "John", "Afternoon", "abc", DateTime.Parse("1/3/15") });
            dta.Rows.Add(new object[] { "John", "Morning", "abc", DateTime.Parse("1/14/15") });
            dta.Rows.Add(new object[] { "John", "Morning", "abc", DateTime.Parse("1/15/15") });
            dta.Rows.Add(new object[] { "John", "Afternoon", "abc", DateTime.Parse("1/26/15") });
            dta.Rows.Add(new object[] { "Mary", "Morning", "abc", DateTime.Parse("1/15/15") });
            dta.Rows.Add(new object[] { "Mary", "Morning", "abc", DateTime.Parse("1/22/15") });
            dta.Rows.Add(new object[] { "Mary", "Evening", "abc", DateTime.Parse("1/23/15") });
            dta.Rows.Add(new object[] { "Mary", "Afternoon", "abc", DateTime.Parse("1/24/15") });
            dta.Rows.Add(new object[] { "Mary", "Morning", "abc", null });
            dta.Rows.Add(new object[] { "Mary", "Evening", "abc", DateTime.Parse("1/26/15") });

            DataTable displayTable = new DataTable();
            DateTime firstDayOfMonth = DateTime.Parse("1/1/15");
            int numberOfDaysInMonth = firstDayOfMonth.AddMonths(1).AddDays(-1).Day;
            DateTime dayCounter = firstDayOfMonth;

            displayTable.Columns.Add("Name", typeof(string));
            for (int i = 0; i < numberOfDaysInMonth; i++)
                displayTable.Columns.Add(dayCounter.ToShortDateString(), typeof(string));
                dayCounter = dayCounter.AddDays(1);

            var results = dta.AsEnumerable()
                .GroupBy(x => x.Field<string>("Emp_Name"))
                .Select(x => new
                    name = x.Select(y => y.Field<string>("Emp_Name")).FirstOrDefault(),
                    shifts = x.Select(y => y.Field<string>("User_Shift")).ToList(),
                    days = x.Select(y => y.Field<object>("Shift_Date")).ToList()

            foreach (var row in results)
                string[] shifts = new string[numberOfDaysInMonth + 1];
                shifts[0] = row.name;
                for (int i = 0; i < row.days.Count; i++)
                    if (row.days[i] != null)
                        int dayOfMonth = ((DateTime)(row.days[i])).Day;
                        string shift = row.shifts[i];
                        shifts[dayOfMonth] = shift;


                DataRow shiftRow = displayTable.Rows.Add(shifts);

            dataGridView1.DataSource = displayTable;

Visual C#, Find records in DataTable A which is or not in DataTable B

By : Simon Cuce
Date : March 29 2020, 07:55 AM
like below fixes the issue Using the Any method may work for you.
Something like this, obviously variable depending on your data structure:
code :
AInB = A.Where(a => B.Any(b => b.ID == a.ID));

ANotInB = A.Where(a => !B.Any(b => b.ID == a.ID));

DataTable.Select() to display summation of records in datatable

By : joseph
Date : March 29 2020, 07:55 AM
wish of those help In my C# project in a DataTable, I need to sum a few columns and display the aggregated record and I am unable to create filter query for that.
code :
var result = (from DataRow s in yourDataTable.Select("filter conditions").AsEnumerable()
              group s by new {g1 = s.Field<string>("Col1"), g2 = s.Field<string>("Col2") } into g
              select new
                  Col1 = g.Key.g1,
                  Col2 = g.Key.g2,
                  Col3 = g.sum(r => r.Field<decimal>("Col3")),
                  Col4 = g.sum(r => r.Field<decimal>("Col4")),
var resultAsDataTable = ConvertListToDataTable(result);

public static DataTable ConvertListToDataTable<T>(IList<T> data)
    PropertyDescriptorCollection props =
    DataTable table = new DataTable();
    for (int i = 0; i < props.Count; i++)
        PropertyDescriptor prop = props[i];
        table.Columns.Add(prop.Name, prop.PropertyType);
    object[] values = new object[props.Count];
    foreach (T item in data)
        for (int i = 0; i < values.Length; i++)
            values[i] = props[i].GetValue(item);
    return table;
Related Posts Related Posts :
  • How can I get back a previously created Excel ListObject?
  • What API can be used to read OAB Files?
  • In linq to entity, how to retrieve objects matching a list of conditions without looping?
  • RESTful web service in C# code
  • C#, Process.Start hide?
  • Multi resolution
  • Alternatives for Crystal Report
  • Lucene.NET, StandardAnalyzer, stopwords and thread-safety
  • How to implement CCAvenue payment gateway option
  • Silverlight and WCF: NotFound error!
  • C# How can I get a list of country codes?
  • Intellisense - Javascript in a string
  • How to change the opacity value of a 3D object
  • Assembly.ReflectionOnlyLoadFrom not working
  • C# Audio - How to time stretch (different tempo, same pitch)
  • Getting certain lines of text c#
  • Can we display Hyperlink from Javascript alert on ASP.NET Page?
  • Can you see programmatically how much amperage a USB device is requesting in windows?
  • What is a way to do a Generic Repository with Entity Framework 4.0 where I have function imports?
  • C# How to determine if a date is within 180 days of now
  • Programmatically hiding properties in a PropertyGrid
  • How do I get a list of fields returned by an OdbcDataReader?
  • ASP.Net Creating Server Side Posting to external website with redirect
  • Adding a tool bar to a web page
  • Convert Audio file into MP3 format using C#
  • Check if a windows service is running?
  • Assembly re-direction in .NET
  • Parse and filter javascript array
  • How to handle a generic dictionary whose types are unknown and don't matter?
  • Distribute images with C# Setup project
  • Is there a way to publish rdl reports programmatically with C#?
  • How to call base.base.method()?
  • How to install Emgu CV wrapper?
  • Interview question - c#
  • .NET Remoting client config creates local object, not remote
  • Is there a possibility to differ virtual printer from physical one?
  • Print barcode which has high scan rate
  • Query string value having "&"
  • Which is best for perfomance?
  • Can we make overloaded controller method in ASP .NET MVC
  • Nested loop in StringTemplate
  • How to get SSID and RSSI for Win7 using C#
  • Send messages to applications on the network (.Net)
  • Detect and prevent/delay windows mobile power off
  • How X509 Certificate renewal does not impact the code?
  • Silverlight: How to make my custom control act like a button
  • C# basic Dictionary Ordering Just need to clear an error
  • Common c# idioms including coalesce ?? operator
  • Why Does Thread.CurrentThread.CurrentCulture Change between Page Rendering and HttpModule.PostRequestHandlerExecute?
  • COM Exception 0x8004005
  • How do I show a message box from inside a class in a class library?
  • LINQ Distinct Query
  • Issue with number guessing game c#
  • Usage of a using statement
  • Building a forms system using DDD
  • How can I programmatically tell in C# if an unmanaged lib is x86 or x64?
  • How do I get an Excel range using row and column numbers in VSTO / C#?
  • .NET 4.0 Memory Mapped Files Performance
  • db4o Indexing problem - Not Working? Poor performance?
  • Realtime Console Output Redirection using Process
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org