Archive for January 10, 2009
How to conditionally show an image, or other control in ASP.NET
January 10, 2009
Leave a comment
Quite often, you want to display an item from a database that may or may not have an associated image. Examples might include a news story, product details, car for sale etc. But you want to avoid the dreaded “redex” if a picture isn’t present.
If you bind the image to an <asp: Image> control you can toggle the Visibility property from true to false, depending on the existence of an image, or image file path in the returned records. Here are some ways to achieve that.
C#:
Visible='<%# Eval("ImageFile")!=DBNull.Value %>'
Or
Visible='<%# Eval("ImageFile")==DBNull.Value ? false: true %>'
Or, if using a DataSource Control, this can be handled in the Item_DataBound Event:
VB.Net
Visible=<%# IIf(Eval("ImageFile") Is DbNull.Value, "False","True") %>'
Or
Visible='<%# Eval("ImageFile")<>DBNull.Value %>'
Hope this helps
Good Luck
Categories: ASP.Net
Limit Text Length in Gridview
January 10, 2009
4 comments
Hi
try this example:
<asp:TemplateField HeaderText="Description"> <ItemTemplate> <asp:Label ID="lblDescription" runat="server" Text='<%# Limit(Eval("Description"),40) %>' > </asp:Label> </ItemTemplate> </asp:TemplateField>
The helper function:
public static string Limit(object Desc, int length) { StringBuilder strDesc = new StringBuilder(); strDesc.Insert(0, Desc.ToString()); if (strDesc.Length > length) return strDesc.ToString().Substring(0, length) + "..."; else return strDesc.ToString(); }
Hope it helps
Good Luck
Categories: ASP.Net
Recent Comments