1

I want to get datetime from SQL database and store it in a DateTime property. At the moment it has value null. I keep getting conversion error. Programming in C# with MVVM.

private void LoadFunctie()
    {
        _myModel = new ObservableCollection<myModel>();
        DataTable DT = new DataTable();
        DT = 
        clsDAC.ExecuteDataTable(Properties.Resources.S_myStoredProcedure);
        foreach (DataRow DR in DT.Rows)
        {
            var x = new clsOrderOverzichtM()
            {
                SomeID = (int)DR[0],//works
                SomeString = DR[1].ToString(),//works
                SomeDate = (DateTime)DR[2]//ERROR

            };
            _myModel.Add(x);
        }
    }

My Property

    private DateTime? _SomeDate;
    public DateTime? SomeDate
    {
        get { return _SomeDate; }
        set
        {
            _SomeDate = value;
            RaisePropertyChanged();
        }
    }

What could be my problem?

1 Answer 1

1

If the column allows null values then you have to check for DBNull when you read from it. The easiest way to do this on a DataRow is with IsNull. The line of code would then be:

SomeDate = DR.IsNull(2) ? null : (DateTime?)DR[2]

The assignment type you are using should then also be nullable or have an acceptable default value.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.