views:

96

answers:

2

hi guyz.

i ve been strugling to find some way to do my required conditional binding, but i am lost :s

i want to use Eval("products_image") in conditional binding in such a way that if product_image exists in images directory then its ok, otherwise it should display "noimage.jpg"

i tried to do it this way:

<%# (File.Exists(("ProductImages/"+Convert.ToString(Eval("products_image"))))) ? ("ProductImages/"+Convert.ToString(Eval("products_image"))) : "ProductImages/noimage_small.jpg" ; %>

i have tried otherways as well, but every time, i mess up with a bunch of errors.

can any one guide me the right way to do this??

+1  A: 
<%# (File.Exists(("ProductImages/"+Convert.ToString(Eval("products_image"))))) ? ("ProductImages/"+Convert.ToString(Eval("products_image"))) : "ProductImages/noimage_small.jpg" ; %>

Quite long and unreadable, isn't it?

I'd suggest adding a method to your code behind or in a <script> tag

// returns the imageFile parameter if the file exists, the defaultFile parameter otherwise
string ImageFileExists(string imageFile, string defaultFile) {
    if (File.Exists(Server.MapPath(imageFile)))
        return imageFile;
    else
        return defaultFile;
}

And then you'd simply use

<%# ImageFileExists("ProductImages/" + Eval("products_image").ToString(), "ProductImages/noimage_small.jpg") %>

Note that I've added a Server.MapPath call to the method so that File.Exists will actually look in the right place.

configurator
+1: Crap, you beat me to it. And with a pretty neat solution too. :)
Jakob Gade
yeah this is great. i have added ImageFileExists method in <script type="text/C#"> tag inside my masterpage. then i have put <%# ImageFileExists("Pr .... into a UserControl Productlist.ascx file, where it was required. (Note that, this .ascx file is then included in a page that is holding that masterpage).but when i run it, it says: error CS0103: The name 'ImageFileExists' does not exist in the current contextwhats solution :(
Muhammad Asif Ali
I think you're missing a runat="server" in your script tag... Did you put one in?
configurator
yes it was missing, i have put it there. but it is still errrroring. CS0103: The name 'ImageFileExists' does not exist in the current context. is there some different way to use it inside a .ascx file?
Muhammad Asif Ali
A: 

yes i did it.. Thanks Allah!!

i just moved the whole <script> tag and System.IO namespace inside the usercontrol .ascx file itself and it did it.

thanx a tones configurator for help :)

Muhammad Asif Ali