Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hello Everyone,
I have a DataTable that contains three columns ID, Shift Start and Shift End
ID | Shift Start | Shift End
1 | 4/12/2018 7:00:00 AM | 4/12/2018 11:00:00 PM
Now the problem is i want to select all the records within this date and time. I tried the following code but not working.
Please help me out.
Thanks in advance.

What I have tried:

// This is key time / time frame in which duration i want to search
DateTime d = Convert.ToDateTime("4/12/2018 22:53");
           string strD = d.ToString("hh:mm:ss tt");
           // Presuming the DataTable has a column named Date.
           string expression;
           expression = "[Shift Start] > #4/12/2018 " + strD + "# AND [Shift End] < #4/12/2018 " + strD + "#";
           DataRow[] foundRows;

           // Use the Select method to find all rows matching the filter.
           foundRows = dt.Select(expression);

           // Print column 0 of each returned row.
           for (int i = 0; i < foundRows.Length; i++)
           {
               MessageBox.Show(foundRows[i][1].ToString());
           }
Posted
Updated 15-Dec-18 2:45am
Comments
Richard Deeming 14-Dec-18 13:14pm    
Your query makes no sense. How many shifts both start after 22:53, and end before 22:53 on the same day?

If you're looking for records which overlap the specified time, then you need to reverse your comparisons. If you're looking for something else, then you need to explain.
Member 14089908 14-Dec-18 22:32pm    
Thanks Richard for your time. Actually i want to search within Shift Start and Shift End please at table give bellow.
ID | Shift Start | Shift End
1 | 4/12/2018 7:00:00 AM | 4/12/2018 23:00:00 PM
Now i want get all the values within 4/12/2018 22:53 this date and time.
Thank you very much.

You can use LINQ like this:
IEnumerable<DataRow> selectedRows = dt1.AsEnumerable()
    .Where(row => (row.Field<DateTime>("Shift Start") <= d) && (d <= row.Field<DateTime>("Shift End")));

foreach (DataRow row in selectedRows)
{
    Console.WriteLine("{0}, {1}", row[0], row[1]);
}
 
Share this answer
 
v3
Comments
Member 14089908 14-Dec-18 22:48pm    
Thanks RickZeeland for you time, i tried you solution but giving me an error. "Specified cast is not valid".

DateTime d = Convert.ToDateTime("4/12/2018 22:53");
IEnumerable<datarow> selectedRows = dt.AsEnumerable()
.Where(row => (row.Field<datetime>("Shift Start") >= d) && (d <= row.Field<datetime>("Shift End")));

foreach (DataRow row in selectedRows)
{
Console.WriteLine("{0}", row[0]);
}
Please help me out.
Thanks
RickZeeland 15-Dec-18 2:38am    
Maybe you are missing a using statement, see complete example below.
Here is my complete example, tested in VS2017 with .NET 4.5.1:
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;

namespace TestForm1
{
    /// <summary>
    /// Codeproject DataTable
    /// </summary>
    public partial class Form1 : Form
    {
        DataTable dt1 = new DataTable();

        public Form1()
        {
            InitializeComponent();
            Test();
        }

        private void Test()
        {
            // Add columns
            dt1.Columns.Add("Shift Start", typeof(DateTime));
            dt1.Columns.Add("employee_id", typeof(string));
            dt1.Columns.Add("employee_name", typeof(string));
            dt1.Columns.Add("Shift End", typeof(DateTime));

            DateTime d = DateTime.Now;

            // Add test data
            dt1.Rows.Add(d.AddMinutes(-10), "1", "PRINCE", d.AddMinutes(-1));
            dt1.Rows.Add(d, "2", "KING", d.AddMinutes(2));
            dt1.Rows.Add(d.AddMinutes(1), "3", "PAUPER", d.AddMinutes(2));

            IEnumerable<DataRow> selectedRows = dt1.AsEnumerable()
                .Where(row => (row.Field<DateTime>("Shift Start") <= d) && (d <= row.Field<DateTime>("Shift End")));

            foreach (DataRow row in selectedRows)
            {
                Console.WriteLine("{0}, {1}", row[0], row[1]);
            }
        }
    }
}
 
Share this answer
 
Nothing to do with your question but never have spaces in column or table names - same goes for file and folder names - just sayin :-)
 
Share this answer
 
Quote:
the problem is i want to select all the records within this date and time. I tried the following code but not working.

You want to know which people were working at a given datetime (dt).
It mean people with [Shift Start] before dt and [Shift End] after dt. the problem is than you did it in reverse, you query is looking for people that [Shift Start] after dt and [Shift End] before dt.
C#
expression = "[Shift Start] < #4/12/2018 " + strD + "# AND [Shift End] > #4/12/2018 " + strD + "#";


Not your question, but another problem you have.
Never build an SQL query by concatenating strings. Sooner or later, you will do it with user inputs, and this opens door to a vulnerability named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input a name like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability, and the crash is the least of the problems, a malicious user input and it is promoted to SQL commands with all credentials.
SQL injection - Wikipedia[^]
SQL Injection[^]
SQL Injection Attacks by Example[^]
PHP: SQL Injection - Manual[^]
SQL Injection Prevention Cheat Sheet - OWASP[^]
How can I explain SQL injection without technical jargon? - Information Security Stack Exchange[^]
 
Share this answer
 
Comments
[no name] 15-Dec-18 8:53am    
SQL injection on a filter Expression for DataTable?
Btw. No vote from my side.
Patrice T 15-Dec-18 9:36am    
Hi,
I agree that this code is safe, but if he concatenate strings to build the query, he will do it the same when dangerous. So, the sooner he learn to do it right with parameters, the better.
string str=4/12/2018 11:00:00
if your searching in sql table
select * from table where endshit='4/12/2018 11:00:00';
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900