I am using .NET 2.0. I have 2 objects one is: PhoneService and the other one is ChartAccount. The relationship between this to is many to many.
public class PhoneService
{
private List<ChartAccount> chartAccounts;
private ChartAccount chartAccount;
public Int64 ID
{ get { return id; }
set { id = value; }
}
public bool Add() { ... }
public bool Update() { ... }
}
public class ChartAccount
{
public Int64 ID
{ get { return id; }
set { id = value; }
}
public bool Add() { ... }
public bool Update() { ... }
public bool Allocate()
{
// this will save data for the bridge table only
}
}
In my clients, i have the following code:
PhoneService service = new PhoneService(Int64.Parse(dataItem.OwnerTableView.DataKeyValues[dataItem.ItemIndex]["ServiceID"].ToString()));
if (service.ChartAccounts == null)
{
Allocation allocation = new ChartAccountAllocation(Int64.Parse(drpdwnlstMainChartAccountAllocation.SelectedValue));
int i=0;
foreach(AllocationItem allocationItem in allocation.Items)
{
service.ChartAccounts[i].Name = allocationItem.Value2;
service.ChartAccounts[i].SplitPercentage = Decimal.Parse(allocationItem.Value1);
service.Allocate();
i++;
}
}
I got an error on the following line saying that Use the “new” keyword to create an object instance.
service.ChartAccounts[i].Name = allocationItem.Value2;
Because CharAccounts is a collection of ChartAccount object and it’s inside Service object so how do I define this thing then?
Thanks
In your foreach loop, you’re doing
service.ChartAccounts[i].Name = allocationItem.Value2, but we already knowservice.ChartAccountsis null (else you wouldn’t have passed the initialifcondition.Before your foreach loop, you need to initialize
service.ChartAccounts, by doingserviceChartAccounts = new List<ChartAccount>(). Then, before you set each value, you need to create a newChartAccountbefore you set itsNameproperty.I’d probably rewrite it something like this:
The important thing to note is that you create the list, and create the
ChartAccountobjects before you use them.