Question

I'm new to Entity Framework and ObjectDataSource. I am trying to get my grid to update an item but get the following error. What am I doing wrong?

Server Error in '/' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[NullReferenceException: Object reference not set to an instance of an object.]
   GalleryApp.Logic.FileActions.UpdateFile(GalleryItemFile newFile) +377

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +92
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +108
   System.Web.UI.WebControls.ObjectDataSourceView.InvokeMethod(ObjectDataSourceMethod method, Boolean disposeInstance, Object& instance) +487
   System.Web.UI.WebControls.ObjectDataSourceView.InvokeMethod(ObjectDataSourceMethod method) +39
   System.Web.UI.WebControls.ObjectDataSourceView.ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues) +1830
   System.Web.UI.DataSourceView.Update(IDictionary keys, IDictionary values, IDictionary oldValues, DataSourceViewOperationCallback callback) +87
   System.Web.UI.WebControls.GridView.HandleUpdate(GridViewRow row, Int32 rowIndex, Boolean causesValidation) +1210
   System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +738
   System.Web.UI.WebControls.GridView.OnBubbleEvent(Object source, EventArgs e) +89
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
   System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object source, EventArgs e) +88
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
   System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +121
   System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +156
   System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +9642610
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18056

Here is my code from ASPX.

<asp:GridView runat="server" DataSourceID="dsFiles" ID="gvFiles" 
        EmptyDataText="No Files Associated with this gallery item yet."
        DataKeyNames="fileID,galleryItem" AutoGenerateColumns="false" CssClass="formtable" OnRowUpdating="gvFiles_RowUpdating">
        <Columns>
            <asp:BoundField HeaderText="filename" DataField="filename" />
            <asp:TemplateField HeaderText="File Type" SortExpression="fileType">
                <ItemTemplate>
                    <%# Eval("FileType.fileType")  %>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:DropDownList runat="server" ID="cboFileType" DataSourceID="dsFileTypes" DataTextField="fileType" DataValueField="fileTypeID" SelectedValue='<%# Eval("FileType.fileTypeID") %>' />
                </EditItemTemplate>
                <InsertItemTemplate>
                    <asp:DropDownList runat="server" ID="cboFileType" DataSourceID="dsFileTypes" DataTextField="fileType" DataValueField="fileTypeID" SelectedValue='<%# Bind("FileType.fileTypeID") %>' />
                </InsertItemTemplate>
            </asp:TemplateField>
            <asp:BoundField HeaderText="Active" DataField="active" />
            <asp:BoundField HeaderText="Resolution" DataField="resolution" />
            <asp:CommandField ShowDeleteButton="true" ShowEditButton="true" ShowHeader="true" />
        </Columns>
    </asp:GridView>

    <asp:ObjectDataSource runat="server" ID="dsFiles"
        TypeName="GalleryApp.Logic.FileActions"
        DataObjectTypeName="GalleryApp.Models.GalleryItemFile"
        SelectMethod="GetFiles"
        InsertMethod="AddFile"
        UpdateMethod="UpdateFile"
        DeleteMethod="DeleteFile" OnUpdating="dsFiles_Updating">
        <SelectParameters>
            <asp:ControlParameter Name="galleryItemID" ControlID="hidGalleryItemID" Type="Int32" />
        </SelectParameters>
        <InsertParameters>
            <asp:ControlParameter Name="galleryItemID" ControlID="hidGalleryItemID" Type="Int32" />
            <asp:Parameter Name="fileTypeID" Type="Int32" />
            <asp:Parameter Name="filename" Type="String" />
            <asp:Parameter Name="active" Type="Boolean" />
            <asp:CookieParameter Name="userCommonName" Type="String" />
            <asp:Parameter Name="resolution" Type="String" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="fileID" Type="Int32" />
            <asp:ControlParameter Name="galleryItemID" ControlID="hidGalleryItemID" Type="Int32" />
            <asp:Parameter Name="fileTypeID" Type="Int32" />
            <asp:Parameter Name="filename" Type="String" />
            <asp:Parameter Name="active" Type="Boolean" />
            <asp:CookieParameter Name="userCommonName" Type="String" />
            <asp:Parameter Name="resolution" Type="String" />
        </UpdateParameters>
        <DeleteParameters>
            <asp:Parameter Name="fileID" Type="Int32" />
        </DeleteParameters>
    </asp:ObjectDataSource>

    <asp:ObjectDataSource runat="server" ID="dsFileTypes"
        TypeName="GalleryApp.Logic.FileTypeActions"
        DataObjectTypeName="GalleryApp.Models.FileType"
        SelectMethod="GetFileTypes">
    </asp:ObjectDataSource>

FileActions is my Logic class. I switched all the methods to static because I saw that in one example but it didn't change anything. I assume it must be talking about the GalleryItemFile object which is one of the entities.

The grid loads click edit then change the filename and click save and I get the yellow screen.

EDIT: Here is the function that is called. The exception occurs the line after the first "else".

public static GalleryItemFile UpdateFile(GalleryItemFile newFile)
    {
        GalleryContext _db = new GalleryContext();

        _db.Database.Log = HttpContext.Current.Response.Write; //Used for Tracing SQL
        int saved = 0;

        GalleryItemFile origFile = _db.GalleryItemFiles.FirstOrDefault(g => g.fileID == newFile.fileID);
        HttpContext.Current.Response.Write(origFile.filename);
        if (origFile == null)
        {
            //ITEM NOT FOUND
        }
        else
        {
            origFile.galleryItem.galleryItemID = newFile.galleryItem.galleryItemID;
            origFile.fileType.fileTypeID = newFile.fileType.fileTypeID;
            origFile.filename = newFile.filename;
            origFile.active = newFile.active;
            origFile.createdOn = DateTime.Now;
            origFile.createdBy = newFile.createdBy;
            origFile.resolution = newFile.resolution;

            saved = _db.SaveChanges();
        }


        if (saved > 0)
        {
            return origFile;
        }
        else { return null; }
    }

While debugging I verified that the origFile is getting retrieved properly. Its the newFile that was sent from the ObjectDataSource that seems to generate the null reference.

EDIT: Here is the model for GalleryItemFile.

Again I am new to Entity Framework, but I thought it would load the galleryItem automatically.

namespace GalleryApp.Models
{
[Serializable]
public class GalleryItemFile
{
    [Key]
    public int fileID { get; set; }
    public virtual GalleryItem galleryItem { get; set; }
    public virtual FileType fileType { get; set; }
    [MaxLength(75)] public string filename { get; set; }
    public bool active { get; set; }
    public DateTime? createdOn { get; set; }
    [MaxLength(150)] public string createdBy { get; set; }
    [MaxLength(50)] public string resolution { get; set; }

}
}


namespace GalleryApp.Models
{
[Serializable]
public class FileType
{
    [Key]
    public int fileTypeID { get; set; }
    [MaxLength(50)] public string fileType { get; set; }
    [MaxLength(15)] public string extension { get; set; }
    [MaxLength(250)] public string icon { get; set; }
    [MaxLength(400)] public string description { get; set; }
    [MaxLength(400)] public string warnings { get; set; }

}
}
Server Error in '/' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 


Line 160:            {
Line 161:                origFile.galleryItem.galleryItemID = newFile.galleryItem.galleryItemID;
Line 162:                origFile.fileType.fileTypeID = newFile.fileType.fileTypeID;
Line 163:                origFile.filename = newFile.filename;
Line 164:                origFile.active = newFile.active;

Source File: c:\Users\holcombelr\SkyDrive\Public\Projects\UHV\GalleryApp\Logic\GalleryItemFileActions.cs    Line: 162 

Stack Trace: 


[NullReferenceException: Object reference not set to an instance of an object.]
   GalleryApp.Logic.FileActions.UpdateFile(GalleryItemFile newFile) in c:\Users\holcombelr\SkyDrive\Public\Projects\UHV\GalleryApp\Logic\GalleryItemFileActions.cs:162

Here is more information. Adding serializable got me one step closer but now the error is on the next line and I've added serializable to all my objects now.

EDIT: Does anyone have an answer to this? I am still having the problem.

Was it helpful?

Solution

I think I figured it out. Apparently when you have subobjects like this you have to include the objects in the DataKeyNames of the gridview.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top