Farooq Ahmed
Farooq Ahmed

Reputation: 11

How To Extract Values From DataTable To List in C#

I Have A Purchase Invoice Form That is Called PurchaseInvoiceForm. I Have A DataGridView In It And Also Used A List To Store Items So I Saved The Data In The Database Successfully.But Whenever I Want To Load Data Back To Form Everything is Fine Excepts I unable To Extract Data From DataTable And Load Back To PurchaseInvoiceCart That is a List.So Here The Code.

    foreach (DataTable row in dtPurchaseInvoice)
        {
            PurchaseInvoice i = new PurchaseInvoice();
            i.PurchaseInvoiceNo =Convert.ToInt32(row["PurchaseInvoiceNo"]);              
        }

Upvotes: 1

Views: 1014

Answers (3)

haldo
haldo

Reputation: 16701

To extract data from a data table use the .Field<T>() extension method from System.Data.DataSetExtensions. Please see the documentation DataRow.Field.

You need to create a list of type PurchaseInvoice and iterate over the DataRow collection table.Rows.

Please see example below:

// create a list for your invoices
List<PurchaseInvoice> invoices = new List<PurchaseInvoice>();

foreach (DataRow row in dtPurchaseInvoice.Rows)
{   //                                   ^ Rows
    // create invoice
    PurchaseInvoice invoice = new PurchaseInvoice();

    // get an int
    invoice.PurchaseInvoiceNo = row.Field<int>("PurchaseInvoiceNo"); 

    // get a string
    invoice.CustomerName = row.Field<string>("CustomerName");

    // get a DateTime
    invoice.PurchaseDate = row.Field<DateTime>("PurchaseDate");

    // get a double
    invoice.PurchaseValue = row.Field<double>("PurchaseValue");

    // add invoice to list     
    invoices.Add(invoice);
}

Using .Field<T>() extension means you do not need to convert/cast the object into the correct type - it is handled by the extension for you.

It also works with nullable fields:

DateTime? date = row.Field<DateTime?>("PurchaseDate");

Upvotes: 1

AGH
AGH

Reputation: 353

You can do it by this way.

List<PurchaseInvoice> objPurchaseInvoiceList = new  List<PurchaseInvoice>();
foreach (DataTable row in dtPurchaseInvoice)
{
    objPurchaseInvoiceList.add(new  PurchaseInvoice{ PurchaseInvoiceNo=Convert.ToInt32(row["PurchaseInvoiceNo"])});                  
}

Upvotes: 0

Hasan Mahmood
Hasan Mahmood

Reputation: 978

foreach (DataRow row in dtPurchaseInvoice.Rows)
    {
        PurchaseInvoice i = new PurchaseInvoice();
        i.PurchaseInvoiceNo =Convert.ToInt32(row["PurchaseInvoiceNo"]);              
    }

Upvotes: 1

Related Questions