Adding DataTable to a List<DataTable>

0

I am trying to add a Data Table to a DataTable list (post a filter operation) that belongs to a kind of modal class. I am getting the below exception on my debug statement _return.SearchResult.Add(_i);. I am getting the same error in my actual statement as well _return.SearchResult.Add(_t);. Kindly help me to identify what is the issue.

Thanks & Regards, S. Sudharsan

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=*******
  StackTrace:
   at *******.*******.searchCMDBData(String SearchString) in D:\GIT_VS2019_WorkSpace\*******\*******\*******.asmx.cs:line 38
   at *******.*******._Default.DoSearch(Object sender, EventArgs e) in D:\GIT_VS2019_WorkSpace\*******\*******.*******\Default.aspx.cs:line 57

        public QR searchCMDBData(string SearchString)
        {
            QR _return = new QR();
            _return.responseType = ResponseType.MESSAGE;
            _return.responseMsg = "Successfully called as expected";
            string INVENTORY_FILE = ConfigurationManager.AppSettings["INVENTORY_FILE_PATH"];

            List<DataTable> _ret = new List<DataTable>();
            _ret = CMDB.GetRequestsDataFromExcel(INVENTORY_FILE);

            foreach (DataTable _i in _ret)
            {
                _return.SearchResult.Add(_i);
                if (_i.TableName == "Inventory Consolidated")
                {
                    DataTable _t = _i.AsEnumerable()
                            .Where(r => r.Field<string>("IP Address").Equals(SearchString) || r.Field<string>("Host Name").Equals(SearchString))
                            .CopyToDataTable();
                    if (_t.Rows.Count > 0)
                    {
                        _return.SearchResult.Add(_t);
                    }
                }
            }
            return _return;
        }
public enum ResponseType { SUCCESS, MESSAGE };

    public class QR
    {
        public ResponseType responseType;
        public string responseMsg;
        public List<DataTable> SearchResult;
    }
c#
list
datatable

1 Answer

0

You have to new up the List<DataTable> SearchResult, otherwise you are trying to insert a value not into an empty list, but into a null list.

You could do this in the constructor of the QR class like this:

public class QR
{
    public ResponseType responseType;
    public string responseMsg;
    public List<DataTable> SearchResult;

    public QR(){
      SearchResult = new List<DataTable>();
    }
}
answered on Stack Overflow Nov 3, 2020 by Jonathan

User contributions licensed under CC BY-SA 3.0