Reputation: 55
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
Upvotes: 1
Views: 80
Reputation: 875
@prasad-telkikar answer is correct. I just wanted to add a few remarks on your code.
it looks like Constants.TAG_OPENING_STOCK
and Constants.TAG_PURCHASE
are well... constants. Probably declared as
public static class Constants
{
public const string TAG_OPENING_STOCK = "TAG_something";
//...
}
So you can improve your code by using a switch
instead:
var ItemsTradingDebitList = new List<string>() ;
switch (Particulars)
{
case Constants.TAG_OPENING_STOCK:
// ...
break;
case Constants.TAG_PURCHASE:
// ...
break;
// etc.
}
If they are not constant but static readonly string
instead then you can't use them in the switch and can use a series of if { } else { }
instead.
Upvotes: 0
Reputation: 16049
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");
}
Upvotes: 4