Binding and DetailsView

Since I’m doing more ASP.Net than I’d normally like to admit to, here’s a really useful little snippet that I struggled with earlier. After my google ninjitsu failed me I turned to figuring it out for myself.

Once I’d wiped the sweat from my forehead I came up with a solution. Whew.

Ok, the problem was that I have a typical master/detail gridview & details view on a form which allows the user to select a row in the grid and then edit the details via the DetailsView. So far so good. I managed to get the whole thing hooked up declaratively using ObjectDataProviders so it felt almost like the XAML i know an love 😉

Anyway next on the agenda was the field validation. I’d re-templated the fields on the DetailsView so we’d got DropDownLists showing predefined lists take from the internal DataModel. Life was good. Throw in a few field validators and we’re good to go. Almost.

Since some of the fields on the form were just TextBoxes, I’d added the typical RequiredFieldValidator, but what about the lengths? These text boxes are mapped VarChar columns on the DB, they had an explicit length. I could hand code the length with the MaxLength property but that just means more work should the DB schema change on me.

If this were XAML we’d have it bound up in no time, but all my attempts in ASP failed miserably.

I know that the DataContext – oops sorry (!) – DataItem must be a DataRow from the table the grid was bound to, so there must be a property giving access to the rows columns. Sure enough, there’s the DataRows Table property we can use. Great! Saved! Effectively what I’d like to do would be bind up the MaxLength property to a DataColumns MaxLength propert. Sound simple. something like

<asp:TextBox MaxLength='<%# Table.Columns["GUR_FORENAME"].MaxLength >’>

Not so fast buster. Unfortunately  the above and all variations I tried didn’t seem to work. Even trying to Bind() to the table didn’t seem to work either

<asp:TextBox MaxLength='<%# (Bind(“Table”) as DataTable).Columns["GUR_FORENAME"].MaxLength >’>

Since Bind(“Table”) returns object, i thought i was in there! No such luck. Dozens of variations later, magic incantations, a full moon and some voodoo, I finally managed to get it working.

The final version of the binding expression I was after looked like this :

<%# Eval("Table.Columns["GUR_FORENAME"].MaxLength") %>

I’m still freaked out by the fact the whole expression has to be inside the quotes. If Bind() really does return an object what the hell is it? If I had time to spare I’d reflector through this, but unfortunately after spending too long on figuring out how to bind the max length, it’s something that will have to wait.

So, it looks like the ASP binding is a bit more flexible than first thought, and not surprisingly , the standard examples hint at!

Reblog this post [with Zemanta]
This entry was posted in General. Bookmark the permalink.

Leave a Reply