Dwight Mendoza Dwight Mendoza - 26 days ago 16
C# Question

e.Result throwing nullreferenceexception

I am trying to use an On_Selecting event to populate linqdatasource, which is in turn use to supply data to a chart. When the event fires, e.Result throws a null reference exception. I haven't been able to figure this one out. Please help.

First, the code for the linqdatasource and the chart:

<asp:Chart ID="MonthlyChart"
runat="server"
DataSourceID="LinqGetChartData">
<series>
<asp:Series Label="#VALX, #VALY"
ChartType="Pie"
Name="Series1"
XValueMember="CostSum"
YValueMembers="SalesMonth"></asp:Series>
</series>
<chartareas>
<asp:ChartArea Name="ChartArea1">
<AxisY Title="Sales Month">
<LabelStyle Format="MMMM" />
</AxisY>
<AxisX Title="Total"></AxisX>
<Area3DStyle Enable3D="True"
WallWidth="10"></Area3DStyle>
</asp:ChartArea>
</chartareas>
</asp:Chart>
<asp:LinqDataSource ID="LinqGetChartData"
runat="server"
ContextTypeName="MegaChallengePapaBobsPizza.Persistence.CustomerEntities"
EntityTypeName=""
OnSelecting="LinqGetChartData_Selecting"
TableName="Customers"></asp:LinqDataSource>


Next, the code for the On_Selecting event:

protected void LinqGetChartData_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
var customerList = Domain.CustomerManager.GetCustomers();
var query = customerList.OrderBy(c => c.OrderDate)
.GroupBy(c => c.OrderDate.ToString("MMMM"),
(c => c.Cost),
(groupKey, totCost) => new SalesResult()
{
SalesMonth = groupKey,
CostSum = totCost.Sum()
});
e.Result = query;
}


Finally, the code that fires the event:

LinqGetChartData_Selecting(sender, e as LinqDataSourceSelectEventArgs);


Any help would be much appreciated. Thanks.

H77 H77
Answer

Since you're calling the event handler in the Page_Load event I assume the variable "e" that you're using is the EventArgs parameter of the Page_Load event. This parameter isn't of type LinqDataSourceSelectEventArgs which results in the following returning null.

e as LinqDataSourceSelectEventArgs

When you try to access the property "Result" of null the null reference exception is thrown.

Since the event handler is assigned in the asp code to the LinqDataSource object you shouldn't need to call it again within Page_Load, unless you have a special reason to do so?