He's Back! The GridView Control Made Me Do It!

Yes, I know. I am just about the worst blogger on earth. Would you believe that I've been on the road pretty much for three months? I know, you're feeling terribly sorry for little ol' me.

Anyway, over the past two weeks I've handled a problem for myself (while recording training videos) and then for two friends, and I figured if we're all having the same trouble, others must be, as well.

Here's the scenario (it's an ASP.NET 2.0 thing):

You create a SqlDataSource retrieving data. You create a GridView control, and bind the GridView control to the SqlDataSource control. All is good--you see all the rows. You can enable editing, make changes, and you look like a winner.

Then, you decide that the SqlDataSource shouldn't be retrieving all the columns from the data source, so you modify the data source to retrieve fewer columns.

Go back to your page, run it, and suddenly, the GridView control isn't showing any data! WTF?

Apparently, late in the beta, Microsoft changed this behavior. Now, if you modify the data source, you'll need to re-add the fields you want displayed within the GridView control yourself. You could have the control auto-populate its fields, but then you'll have to do extra work if you want to convert any of the columns into template fields.

The fun isn't over, however. Now, you can view the data, and you can even edit data. But your changes won't save! (And here is where I spent around 4 hours one night, apparently because I'm stupider than most.)

The solution is (after much trial and error) that when you modified the data source, and stripped the GridView control of all its fields, you also reset the GridView control's DataKeyNames property. In order for the automatic edit/save mechanism to work, the GridView control needs to know what its data's primary key field(s) is/are, and without a value in the DataKeyNames property, it hasn't a clue.

Therefore, the solution is simple (once you know it). You must also reset the DataKeyNames property of the GridView control.

The moral of this story, kids? Just 'cause something works late in the beta doesn't mean it works when the product ships. Oops, did I say that?

Published Friday, December 09, 2005 6:14 PM by KenG
Filed under:

Comments

No Comments