Sunday, March 7, 2010

How do I display a path stored in a field as an image?


Do you have an example of how we can display the image by using the DataFormatString and HTMLEncode? Basically, our database has a field "photo_url" which store the path to the photo in the file system. Can it behave like an image field in terms of presentation?

Please try the following:

1. Start the code generator, click on the name of your project and press "Design" button, select the data controller name and add a new field to the data controller.

2. If the name of the image field is "PhotoPath" then name the new field "PhotoPathImage".

3. Set the type of the new field to "String".

4. Set "Allow null values." to true.

5. Check "The value of the field is computed at runtime" and enter the same snippet from the data controller's command command1 that selects the actual field "PhotoPath". For example, the Northwind's database Employees.PhotoPath will look as follows:


6. Assign a label to the new field. For example, "Photo Path"

7. Uncheck HTML encoding.

8. Enter <img src="{0}"/> as a data format string.

9. Save the field.

10. Add a new data field to grid1 or editForm1 and set its FieldName to PhotoPathImage.

The field will be presented as an image.

1 comment:

Paul Ward said...

I believe that you're better off doing this through a calculated field inside of the controller using a RowBuilder attribute.

Adding the img src directly to the data format field causes the img src to show up in the export and reports.

Instead, create a method in the controller helper class like the following:

[RowBuilder("Employees", RowKind.Existing)]
protected void PrepareUserRow()
string photoPath = (string)SelectFieldValue("PhotoPath");
UpdateFieldValue("PhotoPath", "<" + "img src=\"" + photoPath + "\"/>");
// I had to mangle the above because the blog system wouldn't let me post an img tag

You can find more about Code OnTime Generator, Data Aquarium Framework, and other great products here.

© 2010 Code OnTime LLC. Intelligent code generation software for ASP.NET. Visit us at