ADO, oh, oh, oh!

In my current project I’m building a Windows Forms application using Infragistics’ formidable UltraGrid. The UltraGrid is impressive and infinitely configurable, but I’ve spent countless hours trying to get it to do, what I believe is, fairly basic stuff. As spider-man nearly said: "with great power comes great complexity".

Recently I was having a problem where I was binding the grid to a DataTable but the grid wasn’t detecting which fields were non-nullable. According to the docs it should know and should not allow empty entries in non-nullable fields. I racked my brains, I ploughed through the documentation, I installed the SDK – nothing.

Then I took a step back and decided to look at the DataTable itself and – duh – AllowDBNull seemed to be true for every column in it. This was nothing to do with the grid – it was what I was doing (or not doing) with ADO. Sorry for cursing you Infragistics, I take it all back...

ADO.Net is not something I’ve spent a huge time with. Sure, I’ve done some basic binding to GridViews and FormViews in ASP.Net, but I’ve never really spent the time getting to know it. In my current project we’re using the ORM tool LLBLGen to generate entities that are bound to the front-end, so I’ve been isolated from ADO for some time.

After a bit of digging I found the answer in the ADO.Net 3.5 Cookbook by Bill Hamilton (O’Reilly). It turns out that when you call DataAdapter.Fill() ADO assumes that you don’t want schema information – such as nullability or datatypes – unless you specifically say so. What I needed to configure was the DataAdapter.MissingSchemaAction property – in this case setting it to MissingSchemaAction.AddWithKey, like so:

SqlDataAdapter adaptor = new SqlDataAdapter(command);
adaptor.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adaptor.Fill(data, tableName);

And, hey presto, the UltraGrid now has knowledge of non-nullable columns in the DataTable.

You can read more about this here: When to Use FillSchema and MissingSchemaAction with the DataAdapter in ADO.NET.

Comments