Search code examples
c#listitemssource

How a list can be added to another list in c#?


I have a page with multiple listViews. I have created some difference lists from DbModels and need to bind these lists to the ListViews. Here what I want is if (Particulars == Constants.TAG_OPENING_STOCK) a list adds to a ItemsTradingDebitList list.

and if(Particulars == Constants.TAG_PURCHASE) another list should add to ItemsTradingCreditList list.

I have tried creating a new list with values and added it to another list using AddRange. But this brings an error Object Reference not set to an instance of an object. list was empty

if (Particulars == Constants.TAG_OPENING_STOCK)
{
    List<string> NewList = new List<string> { Particulars, Amount };
    ItemsTradingDebitList.AddRange(NewList);              
}
if(Particulars == Constants.TAG_PURCHASE)
{
    List<string> NewList = new List<string> { Particulars, Amount };
    ItemsTradingDebitList.AddRange(NewList);
}
if(Particulars == Constants.TAG_SALES)
{
    List<string> NewList = new List<string> { Particulars, Amount };
    ItemsTradingCreditList.AddRange(NewList);
}

My expected result is a list of all added lists. What I am getting is an error


Solution

  • I believe "Particulars", "Amount" are strings, if both are strings, then you can directly add it to the list, here no need to create new list

    something like,

    ItemsTradingDebitList.Add("Amount");    
    ItemsTradingDebitList.Add("Particulars");   
    

    As per error mentioned in question, I guess you have not initialized list i.e. ItemsTradingDebitList. If that is the case then before first if condition create an instance of ItemsTradingDebitList

    like

    List<string> ItemsTradingDebitList = new List<string>();
    

    This will resolve your problem,

    List<string> ItemsTradingDebitList = new List<string>(); //This might be missing in your code
    if (Particulars == Constants.TAG_OPENING_STOCK)
    {
        ItemsTradingDebitList.Add("Amount");    
        ItemsTradingDebitList.Add("Particulars");   
    }
    if(Particulars == Constants.TAG_PURCHASE)
    {
        ItemsTradingDebitList.Add("Amount");    
        ItemsTradingDebitList.Add("Particulars"); 
    }
    if(Particulars == Constants.TAG_SALES)
    {
        ItemsTradingDebitList.Add("Amount");    
        ItemsTradingDebitList.Add("Particulars"); 
    }