PDA

View Full Version : call a function in codebehind from aspx


10inja
07-18-2009, 08:41 PM
Hi all.
hope this is the right place to post this.
I wanted to call a function that will search a subfolder and return the first file it finds.. how do I call this function from the web page? what's the correct format?
also, is that the right approach?

in the web page:
<asp:ImageID="Image2"runat="server"Width=250pxImageUrl="GetFirstImage("Testing")"/>

in the codebehind:
using System.IO;
public partialclass _Default : System.Web.UI.Page
{
private FileInfo[] rgFiles;
protected void Page_Load(object sender, EventArgs e)
{
}
public string GetFirstImage(string Stock)
{
DirectoryInfo di = newDirectoryInfo(HttpRuntime.AppDomainAppPath.ToSt ring() + "images\\" + Stock);
rgFiles = di.GetFiles("*.jpg");
return"~/images/" + Stock + "/" + rgFiles[0];
}
}

CrystalCMS
07-19-2009, 01:31 AM
This is the standard .NET data binding approach that's often used with GridView, ListView etc.

You're close to having it working, but you have a little syntax problem in your data binding expression. Try:
<asp:ImageID="Image2" runat="server" Width=250px ImageUrl='<%# GetFirstImage("Testing") %>' />
You can read more about data binding expressions here:http://msdn.microsoft.com/en-us/library/ms178366.aspx

There are a couple of other things I did notice in your code sample:

Unless you really need it to be 'public', you can reduce the access modifier on the GetFirstImage method down to protected.
You might also have a bug in the GetFirstImage method because it does not include any defensive code mechanism; e.g. you could potentially be attempting to access to an array element does not actually exist with:
return"~/images/" + Stock + "/" + rgFiles[0]If there are no jpg images in the target folder an exception will be thrown.


I hope that helps - good luck
Joe

10inja
07-19-2009, 12:37 PM
Thanks.. that got me going. I could've swore I tried that already..
I even tried <%= tag..
<asp:Image ID="Image2" runat="server" Width=250px ImageUrl= '<%# GetFirstImage(DataBinder.Eval(Container.DataItem,"Stock").ToString()) %>' />
so.. now it's working and thanks for the help on the code part as well.
I udpated the code to do the sanity checking:
protected string GetFirstImage(string Stock)
{
Stock = Stock.Trim();
FileInfo[] rgFiles;
DirectoryInfo di = new DirectoryInfo(HttpRuntime.AppDomainAppPath.ToStrin g() + "images\\" + Stock);
rgFiles = di.GetFiles("*.jpg");
if (rgFiles.GetUpperBound(0) > -1)
return "~/images/" + Stock + "/" + rgFiles[0];
else return "";
}

thanks

CrystalCMS
07-19-2009, 01:21 PM
Excellent - I'm glad you worked it out.