TransWikia.com

To convert not null datetime into null. c#

Stack Overflow Asked by Mashail Furqan on January 23, 2021

I would like to make my not null DateTime column null when I do the sum of the entire table so that I do not get any value for date time 1/1/0001 12:00:00. I would like to add whatever possible statement into this method. I tried to do parse it but it doesn’t work, but for Amount it’s perfectly fine.

private void SumOfRecords_Button(object sender, RoutedEventArgs e)
{
    ObservableCollection<Receipt> receipts = new ReceiptDAO().GetAllReceiptsFromPiName();
    Receipt receipt = new Receipt();

    if (receipt.DateTime != null)
    {
        Receipt receipt0 = new Receipt()
        {
            DateTime = DateTime.TryParse(),
            Amount = new ReceiptDAO().SumOfRecords("Amount")
        };

        receipts.Add(receipt);
        this.Dispatcher.Invoke(() => ReceiptList.ItemsSource = receipts);
    }
}

This is the method for SumOfRecords where I am writing my query.

public double SumOfRecords(string columnName)
{
    ObservableCollection<Receipt> receipts = new ReceiptDAO().GetAllReceiptsFromPiName();
    Receipt receipt = new Receipt();
    string commandstring;
    commandstring = "select Sum(" + columnName + ") from " + getTable();
    
    using (SQLiteConnection connection = ConnectToDatabase())
    {
        using (SQLiteCommand command = new SQLiteCommand(commandstring, connection))
        {
            using (SQLiteDataReader reader = command.ExecuteReader())
            {
                reader.Read();
                return reader.GetDouble(0);
            }
        }
    }
}

One Answer

Just ignore dates when you calculate the sum. Assuming you're using sql server for database.

var where = " WHERE Table.Date <> '0001/01/01 00:00:00'";
commandstring = "select Sum(" + columnName + ") from " + getTable() + where;

You can pass where as a parameter to the method to make it reusable. Based on what database you're using, you may want look into date comparison. Otherwise the concept remains the same.

Correct answer by Pirate on January 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP