Reputation: 8788
How the heck do I call Eval() from codebehind? I know this is a front-end shortcut for something like DataBinder.Eval(Container.DataItem, "name"), but I cannot get this damn thing to compile. I am missing the proper method parameters, I think. I want to turn something like this:
<asp:Image ID="imgLogo" runat="server" ImageUrl='<%# Eval("name") %>'/>
into:
<asp:Image ID="imgLogo" runat="server" ImageUrl='<%# GetImagePath(???) %>'/>
w/ code-behind:
protected string GetImagePath(????)
{
//some code
return "some/logical/path" + Eval("name");
}
The asp:Image control is in a repeater that is bound to a SqlDataReader.
Upvotes: 18
Views: 28620
Reputation: 7352
Ruben's answer works, but in case you need to include some argument for ????
and want to avoid calling Eval
, here is the more complete answer.
<asp:Image ID="imgLogo" runat="server" ImageUrl='<%# GetImagePath("SomeData") %>'/>
And code behind:
protected string GetImagePath(string someDataHere)
{
object dataItem = null;
try
{
dataItem = Page.GetDataItem();
}
catch (InvalidOperationException ex) // Thrown when the control is not data bound
{
return null;
}
string name = DataBinder.Eval(dataItem, "name").ToString();
return "some/logical/path/" + someDataHere + "/" + name;
}
Upvotes: 0
Reputation: 10609
Another simple way to do this is to use the overload of Eval that takes a format, the aspx becomes:
<asp:Image ID="imgLogo" runat="server" ImageUrl='<%# Eval("name", "some/logical/path/{0}") %>'/>
Upvotes: 2
Reputation: 532745
Have you tried something like:
<asp:Image ID="imgLogo" runat="server' ImageUrl='<%# GetImagePath( Convert.ToString( Eval("name") ) ) %>' />
and
protected string GetImagePath( string image )
{
return "some/logical/path/" + image;
}
Upvotes: 5
Reputation: 15555
Eval
is a method on Page
(on TemplateControl
actually, which means that it's also present on UserControl
). So you don't need to pass any special parameters:
protected string GetImagePath()
{
//some code
return "some/logical/path" + Eval("name");
}
Caution: you can only call Eval
while databinding, but that's implicitly the case for <%# Eval(...) %>
too, so that shouldn't pose a problem.
If you want the actual object you're binding to, use GetDataItem()
, as Eval(x)
basically means DataBinder.Eval(GetDataItem(), x)
.
Upvotes: 17
Reputation: 78152
protected void rProducts_ItemDataBound(object sender, RepeaterItemEventArgs e) {
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) {
Image ProductImage = (Image)e.Item.FindControl("ProductImage");
ProductImage.ImageUrl = DataBinder.Eval(e.Item.DataItem, "ProductImageUrl");
// Or strongly typed
Product product = (Product)e.Item.DataItem;
ProductImage.ImageUrl = product.ProductImageUrl;
}
}
Upvotes: 4