Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullReferenceException when setting AutoSizeMode to AllCells in DataGridView

I am manually binding an entity framework code first table to a datagridview. When I set the AutoSizeMode to AllCells and add an instance to the table I get a NullReferenceException during Add.

The code runs like this:

dbContext.Persons.Load();
myDataGridView.DataSource = dbContext.Persons.Local.ToBindingList();

myDataGridView.Columns[ "Description" ].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

Person p = new Person();
p.Name = "Tester Alfred";
p.Description = "Description"; //no more properties, only those two (Id Property is annotated as [Key]

dbContext.Persons.Add( p ); // this throws a NullReferenceException

Here is the relevant part from the stack trace:

System.Data.Entity.Core.Objects.ObjectContext.AddSingleObject(EntitySet entitySet, IEntityWrapper wrappedEntity, String argumentName)
   bei System.Data.Entity.Core.Objects.ObjectContext.AddObject(String entitySetName, Object entity)
   bei System.Data.Entity.Internal.Linq.InternalSet`1.<>c__DisplayClassd.<Add>b__c()
   bei System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
   bei System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
   bei System.Data.Entity.DbSet`1.Add(TEntity entity)

The table Persons is otherwise empty. When I remove the AutoSize - Instruction everything is fine.

Plattform: WInForms in .Net 4.5.1 using Studio 2013; Running Win8 Pro, EF 6.1.3

Edit: Removed typo that introduced a second gridview

like image 416
Mario The Spoon Avatar asked Apr 10 '15 13:04

Mario The Spoon


2 Answers

AutoSize all cells means the data grid view needs to evaluate the result for each column. The EF needs to supply the result for each row. It appears that you are probably binding to a foreign key column. If the value in the row does not match up to a row in the foreign table, then the datagridview will throw this error. The EF has a problem where the value in the table MUST match the value in the foreign table case-wise sensitive ... regardless of whether or not SQL is case-sensitive. The EF is using the CLR to perform entity matching ... which is case-sensitive

like image 80
Marc Johnston Avatar answered Nov 18 '22 23:11

Marc Johnston


Try adding the data first and then use it

myDataGridView .Columns[ "Description" ] .AutoSizeMode  = 
DataGridViewAutoSizeColumnMode .AllCells ;
like image 1
Manoj Avatar answered Nov 19 '22 01:11

Manoj