Solved

How do I get multiple column values from data table.

Posted on 2016-09-21
4
52 Views
Last Modified: 2016-09-21
Hi guys,

I have Person table and
dt has this table values.

 DataTable dt = getPersonTable();

Person table
I want to have FirstName and LastName for PersonId = 4 from DataTable, dt.

How can I accomplish this?
0
Comment
Question by:Isabell
4 Comments
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 41808406
see https://msdn.microsoft.com/en-us/library/system.data.datatable.rows(v=vs.110).aspx

something like
PersonID = dt.Rows(0).Columns(0)
LastName = dt.Rows(0).Columns(1)
....
0
 
LVL 50

Assisted Solution

by:Ryan Chong
Ryan Chong earned 100 total points
ID: 41808413
you can also try:

DataRow[] dr = dt.Select("PersonId = '4' ")

Open in new window


then refer to DataRow collection instead.
0
 
LVL 9

Accepted Solution

by:
Paweł earned 400 total points
ID: 41808418
you can also use linq

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
    class Program
    {
        static DataTable dt = new DataTable();
        static void Main(string[] args)
        {
            dt.Columns.Add(new DataColumn("Id", typeof(int)));
            dt.Columns.Add(new DataColumn("LastName", typeof(string)));
            dt.Columns.Add(new DataColumn("FirstName", typeof(string)));
            dt.Columns.Add(new DataColumn("BirthDate", typeof(DateTime)));

            NewRow(1, "paul", "chooch", new DateTime(1984, 1, 31));
            NewRow(2, "tom", "chooch", new DateTime(1988, 8, 28));
            NewRow(3, "john", "smith", new DateTime(1963, 7, 14));
            NewRow(4, "jane", "doe", new DateTime(1992, 4, 13));

            var output = dt.AsEnumerable()
                .Where(dr => dr.Field<int>("Id") == 2)
                .Select(dr => new
                {
                    fName = dr.Field<string>("FirstName"),
                    lName = dr.Field<string>("LastName")
                  
                    
                }).FirstOrDefault();

            Console.WriteLine( output.fName + " " + output.lName);

        // or combine mine and Ryan's approach
        var output2 = dt.Select("Id = 2")
                .Select(dr => dr.Field<string>("FirstName") + " " + dr.Field<string>("LastName") ).First();

            Console.WriteLine(output2);
        }

        static void NewRow(int id, string lName, string fName, DateTime bDate)
        {
            var dr = dt.NewRow();
            dr.SetField("Id", id);
            dr.SetField("LastName", lName);
            dr.SetField("FirstName", fName);
            dr.SetField("BirthDate", bDate);
            dt.Rows.Add(dr);
        }
    }
}

Open in new window

0
 
LVL 42

Expert Comment

by:zephyr_hex (Megan)
ID: 41809056
Here is how I would approach it:
//select record(s) to data rows
DataRow[] childRow = dt.Select("PersonId = 4");
//if at least one record is found
if(childRow.Any())
{
    //copy rows to a datatable
    DataTable childDt = childRows.CopyToDataTable();
}

Open in new window



or, if you just want the First and Last name, you can do:

var test = from row in dt.AsEnumerable()
                    where row.Field<int>("PersonId") == 4
                    select new {First = row.Field<string>("FirstName"), Last = row.Field<string>("LastName")};

Open in new window

0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
ASCX file or a newer alternative? 1 34
.net and XML report from SCCM 5 20
Help with error when uploading excel file 3 26
Batch file or script with password 22 42
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question