0

I receive an "Object reference not set to instance of an object" error while trying to convert a DataTable into a viewmodel containing rows and columns.

ViewModel

public class ViewModel
{
        public List<ColumnViewModel> Columns { get; set; }
        public List<RowViewModel> Rows { get; set; }
}

    public class ColumnViewModel
    {
        public string Name { get; set; }
    }

    public class RowViewModel
    {
        public List<CellValueViewModel> Values { get; set; }
    }

    public class CellValueViewModel
    {
        public string Value { get; set; }
    }

Model

    ViewModel myViewModel = new ViewModel();
    CellValueViewModel myCellValueViewModel = new CellValueViewModel();
    RowViewModel myRowViewModel = new RowViewModel();
    foreach (DataColumn column in GridData.Columns)
    {
        ColumnViewModel myColumnViewModel = new ColumnViewModel();
        myColumnViewModel.Name = column.ColumnName;
        myViewModel.Columns.Add(myColumnViewModel);
    }

The error occurs at myViewModel.Columns.Add(myColumnViewModel); I do not understand why this is happening since Ive instantiated each object that Im using here.

1 Answer 1

2

Well, you never assigned the Columns property a value. Make sure you have instantiated it before attempting to add values to this list:

ViewModel myViewModel = new ViewModel();
myViewModel.Columns = new List<ColumnViewModel>();
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.