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
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
Try adding the data first and then use it
myDataGridView .Columns[ "Description" ] .AutoSizeMode =
DataGridViewAutoSizeColumnMode .AllCells ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With