This is a migrated thread and some comments may be shown as answers.

Data Exception In Between AddingRow and AddedRow Event

3 Answers 190 Views
GridView
This is a migrated thread and some comments may be shown as answers.
Christopher
Top achievements
Rank 1
Christopher asked on 28 Nov 2013, 05:31 PM
I'm implementing an inventory program that will view, edit, add, and remove rows from an sql database using the radGridView. The program was started in visual studio 2013 ultimate and did not have this issue. When I opened it in visual studio 2012 ultimate, I suddenly get a data exception sayng "Object reference not set to an instance of an object" when trying to add the first row to the gridview. Through debugging found that it happens in between the useraddingrow event and the useraddedrow event. Once the exception happens, I can correct it by changing the datasource to another table and back again but not before it happens the first time. The exception also happens with empty event handlers (commented out)
private void radGridView3_UserAddingRow(object sender, GridViewRowCancelEventArgs e)
    { }
private void radGridView3_UserAddedRow(object sender, GridViewRowEventArgs e)
    {
        //dbContext.SaveChanges();
      }
private void radGridView3_CellBeginEdit(object sender, GridViewCellCancelEventArgs e)
    { }
private void radGridView3_CellEndEdit(object sender, GridViewCellEventArgs e)
    { }
private void radGridView3_UserDeletedRow(object sender, GridViewRowEventArgs e)
    { }
Above are the event handlers I comment out while still getting the error.

This is how I assign the data source
MaintenanceEntitiesDB dbContext = new MaintenanceEntitiesDB();           
public Form1()
{
    InitializeComponent();
    // Set initial data source to assets table
    dbContext.Assets.Load();
    radGridView3.DataSource = dbContext.Assets.Local.ToBindingList();
}
The same thing is done on radiobutton checkedchanged to switch between assets and consumables table.

It seems that the data exception HAS to happen before it will let me add a row.

Attached is the error box as well. What doesn't make sense is I did not implement any exception handling that displays the exception message so the program should in theory crash when this message pops up...

Using ADO.NET entity for database access, C#, .net 4.0

I have a build from VS2013 deployed currently with roughly the same setup for the gridview that is not getting the exception.

NOTE: When I switched to VS2012, the gridview was re-added and configured to work with 2012

3 Answers, 1 is accepted

Sort by
0
George
Telerik team
answered on 03 Dec 2013, 01:25 PM
Hello Christopher,

Thank you for contacting us.

Your case seems very specific, especially since it is occurring only after the upgrade. In this case I can suggest you to try to override the method which is executed when such exception occurs. The method is called OnDataError and is in the RadGridView class. If you do not find this helpful I would need to kindly ask you to provide me with a sample application in which the error is reproducible. I would recommend you to also try with a clean database since database constraints may cause such behavior.

Looking forward to your reply.

Regards,
George
Telerik
TRY TELERIK'S NEWEST PRODUCT - EQATEC APPLICATION ANALYTICS for WINFORMS.
Learn what features your users use (or don't use) in your application. Know your audience. Target it better. Develop wisely.
Sign up for Free application insights >>
0
Christopher
Top achievements
Rank 1
answered on 03 Dec 2013, 03:28 PM
I was able to manually bypass the AddedRow event by applying the change to the local context and then saving it in the AddingRow event:
private void GridViewMainUserAddingRow(object sender, GridViewRowCancelEventArgs e)
        {
            // Asset validation
            if (dataSource == "Asset")
            {
                // Ensure no fields are null
                // Id can be null as it is assigned later
                if (e.Rows[0].Cells[1].Value == null ||
                    e.Rows[0].Cells[2].Value == null ||
                    e.Rows[0].Cells[3].Value == null ||
                    e.Rows[0].Cells[4].Value == null ||
                    e.Rows[0].Cells[5].Value == null ||
                    e.Rows[0].Cells[6].Value == null ||
                    e.Rows[0].Cells[7].Value == null)
                {
                    // Cancel add and display error message if fields are null
                    e.Cancel = true;
                    MessageBox.Show("Please ensure all fields are specified.", "Data Exception", MessageBoxButtons.OK);
                    return;
                }
                else
                {
                    // Temporary context used to retrieve the next available Id without affecting the GridView
                    EntitiesMaintenance dbContextTemp = new EntitiesMaintenance();
                    // Query used to retrieve the next available Id from the database
                    System.Data.Entity.Infrastructure.DbSqlQuery<Asset> sQuery = dbContextTemp.Assets.SqlQuery("manual query to get the next available id used for tracking");
                    try
                    {
                        // Iterate the query
                        foreach (Asset aTemp in sQuery)
                        {
                            // Assign the returned Id
                            e.Rows[0].Cells[0].Value = aTemp.Id;
                        }
                        // Initialize new asset to add to database
                        Asset a = new Asset();
                        a.Id = (int)e.Rows[0].Cells["Id"].Value;
                        a.Name = (string)e.Rows[0].Cells["Name"].Value;
                        a.LocID = (int)e.Rows[0].Cells["LocID"].Value;
                        a.Mfg = (string)e.Rows[0].Cells["Mfg"].Value;
                        a.Model = (string)e.Rows[0].Cells["Model"].Value;
                        a.Price = (decimal)e.Rows[0].Cells["Price"].Value;
                        a.Serial = (string)e.Rows[0].Cells["Serial"].Value;
                        a.Tag = (string)e.Rows[0].Cells["Tag"].Value;
                        // Insert asset in database
                        dbContextTemp.Assets.Load();
                        dbContextTemp.Assets.Local.Add(a);
                        // Initialize new asset history to add to database
                        AHistory aHistory = new AHistory();
                        aHistory.AssetID = (int)e.Rows[0].Cells["Id"].Value;
                        aHistory.Id = DateTime.Now;
                        aHistory.LocID = (int)e.Rows[0].Cells["LocID"].Value;
                        // Insert asset history in database
                        dbContextTemp.AHistories.Load();
                        dbContextTemp.AHistories.Local.Add(aHistory);
                        //GridViewMain.Rows.Remove(e.Rows[0]);
                        //e.Rows[0].Delete();
                        try
                        {
                            // Try to save the changes to the database
                            dbContextTemp.SaveChanges();
                        }
                        catch (Exception)
                        {
                            // Exception will fire due to inconsistencies but the changes will be saved
                        }
                        finally
                        {
                            // Update GridView data
                            RadioButtonAssetsCheckedChanged(this, new EventArgs());
                        }
                    }
                    catch (Exception ex)
                    {
                        // Cancel add and display error message
                        // Usually if query fails
                        e.Cancel = true;
                        MessageBox.Show(ex.Message, "Query Exception", MessageBoxButtons.OK);
                        return;
                    }
                }
            }
            // Cancel the row add to prevent UserAddedRow event from firing
            e.Cancel = true;
        }
I'm thinking it may have been an issue with the global context as in the above code, using the global context threw another error when trying to manually add the row. Switching to a local context, the error is not reproduced. 
0
George
Telerik team
answered on 06 Dec 2013, 11:57 AM
Hi Christopher,

I am glad that you were able to resolve your issue. Should you have any other questions, do not hesitate to ask.

Regards,
George
Telerik
TRY TELERIK'S NEWEST PRODUCT - EQATEC APPLICATION ANALYTICS for WINFORMS.
Learn what features your users use (or don't use) in your application. Know your audience. Target it better. Develop wisely.
Sign up for Free application insights >>
Tags
GridView
Asked by
Christopher
Top achievements
Rank 1
Answers by
George
Telerik team
Christopher
Top achievements
Rank 1
Share this question
or