ASP.Net Listview with FileUpload Control & LinqDataSource
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:
And the insert
The source for the above would look like this:
See that we’re just wrapping the image in a link and shrinking it down.
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.
Then we’re going to going to override the LINQ inserting and inserted events:
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.
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.
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.