How to get column value from Datatable

19,681

You should be able to follow the example in the link provided.

Suppose your have a DataTable like this

            DataTable dt = new DataTable();
            dt.Columns.Add("UserID");
            dt.Columns.Add("FullName");
            dt.Columns.Add("DateBooked");
            dt.Columns.Add("RoomQty");
            dt.Columns.Add("NoofNights");

            dt.Rows.Add(1, "John Doe", DateTime.Now.AddDays(-7).Date, 2, 3);
            dt.Rows.Add(2, "Jack Sparrow", DateTime.Now.AddDays(-14).Date, 1, 1);
            dt.Rows.Add(3, "Arthur Wilson", DateTime.Now.AddDays(-10).Date, 2, 2);
            dt.Rows.Add(4, "Amy Jackson", DateTime.Now.AddDays(-5).Date, 4, 2);
            dt.Rows.Add(5, "Tim Lee", DateTime.Now.AddDays(-1).Date, 1, 5);
            dt.Rows.Add(2, "Jack Sparrow", DateTime.Now.AddDays(-5).Date, 3, 2);

and your input parameters are

            int userInput = 2;
            DateTime dateBooked = DateTime.Now.AddDays(-14).Date;
            int roomQty = 1;
            int noOfNights = 1;

You can get the 'FullName' column value like this (provided you will have a single record based on your where conditions)

            string FullName = (from DataRow dr in dt.Rows
                               where Convert.ToInt32(dr["UserID"]) == userInput &&
                               Convert.ToDateTime(dr["DateBooked"]) == dateBooked &&
                               Convert.ToInt32(dr["RoomQty"]) == roomQty &&
                               Convert.ToInt32(dr["NoofNights"]) == noOfNights
                               select (string)dr["FullName"]).FirstOrDefault();
Share:
19,681
user1270384
Author by

user1270384

programmer

Updated on June 04, 2022

Comments

  • user1270384
    user1270384 almost 2 years

    I'm trying to get row values from a datatable with column value matching the user input.

    I found this link:

    How to get a specific column value from a datatable?

    But I'm not sure about it because I want to be able to say

    where userID =@userinput and DateBooked =@DateBooked and 
    RoomQty=@RoomQty and NoofNights=@NoofNights
    

    .

    Would this example work for my situation?