Category Archives: Asp.Net Controls

Generic function to display images on webpage asp.net

Hi fellas,

I am writing this post after a long time. This new year I am back at blogging to help the software developers in writing better code .

Ever need of a generic/common function to display the images on website?
In normal practice, whenever we need to show an image, we used to directly write
Image.Src= “/userfiles/abc.jpg”;

This can be painful sometimes if your folder path gets changed,  in that case you need to replace the folder (userfiles) everywhere.

Smart and better way is to create a common function that will display images. What you need to do is to call this method every time.


Method:

public string ShowImage(string ImageName)
{
string ReturnVal = string.Empty;

if (File.Exists(System.Web.HttpContext.Current.Server.MapPath(“~/userfiles/” + ImageName)) == true)
{
ReturnVal = VirtualPathUtility.ToAbsolute(“~/userfiles/” + ImageName);
}
else
{
ReturnVal = VirtualPathUtility.ToAbsolute(“~/Images/ImageNotAvailable.jpg”);
}

return ReturnVal;
}


Usage:

imgThumbnail.ImageUrl = ShowImage(“abc.jpg”);


Explanation:

This method, takes a string parameter as image name to display. Then it checks that if the particular image exists or not.
If the image exists on the specified path then it returns the image name with full path (userfiles/abc.jpg) else it returns the alternate image path, which is imageNotAvailable.jpg.

This way if the image is not founded on server then user will be shown a imageNotAvailable.jpg

Thats it for now.

Advertisements

Traverse / Loop through all form controls in asp.net

This post explains that how to traverse (loop through) all form controls in asp.net page.

foreach (System.Web.UI.Control ctrl in this.form1.Controls)
{
//here your code
}

Further if you want to get the state or data or manipulate the control, use the below code:
Here I am checking that at least one DropDownList item is selected out of all DropDownLists in the current webform.

bool isSelected = false;

foreach (System.Web.UI.Control ctrl in this.form1.Controls)
{

if (ctrl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
{
DropDownList ddl = (DropDownList)ctrl;

if (ddl.SelectedItem.Text != "")
{
isSelected = true;
break;
}
}

}

if (isSelected == true)
{
Response.Write("selected");
}
else
{
Response.Write("none selected");
}