ASP.Net Listview with FileUpload Control & LinqDataSource

2009 March 19
by echostorm

So this was a little harder than I thought it would be.  I’m still a little shocked that it wasn’t a more common question.  So here is what we’re going for, a ListView databound to a LinqDatasource which has a column with an image path.  We want to show that image in the grid and allow for uploading new images to new and existing rows. Like this:

croppercapture1

And the insert

croppercapture2

The source for the above would look like this:

croppercapture3

See that we’re just wrapping the image in a link and shrinking it down. 

croppercapture4

Again, no biggie, just a regular FileUpload control.

Now lets look at the real magic thats going to make this work.  The first thing we need is a way to find the control from our code-behind.  This is pilfered from everyone’s friend Jeff Atwood from over at Coding Horror.

croppercapture5

Then we’re going to going to override the LINQ inserting and inserted events:

croppercapture6

This should be pretty straightforward.  We grab a handle to the FileUpload object and create the server path (I know, it should be inside the IF but I don’t want to redo the screenshot)  Then we save the file to the server.

croppercapture7

Now after the row has been inserted we’ll check that FileUpload control again, get the row that was just inserted, set the path and update the row just in time for the postback.

croppercapture81

You could probably wrap the whole thing up in an UpdatePanel and make it all slick and Ajaxy but I think what we’ve got here is pretty neat as is.  Enjoy.

One Response leave one →
  1. 2009 September 11

    Thanks for posting this. I’ve just spent most of the day trying to figure out how to do this. (And I would never have come up with this solution in a million years.)

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS