System.Web.UI.WebControls Namespace Image Class
Initializes a new instance of the Image class.
[ VB ]
Public Sub New ( )
[ C# ]
public Image ( );
[ C++ ]
public: Image ( );
[ JScript ]
public function Image ( );
Use this constructor to programatically initialize a new instance of the Image control at run time.
This method is useful when there is need to conditionally add or insert a new Image control at some specified location on the page at run time, particularly when the number of Image controls to generate are unknown at design time. Typical applications include programmatically adding Image controls to dynamically generated list controls, such as the Repeater, DataList or DataGrid.
Below is some code snippet from our sample search results page that illustrates, among others, how to programatically add Image controls to the ItemTemplate of a DataList control that is generated dynamically at run time. How many images to render depends on how many records are returned in the results set.
void buildItemTemplate ( Control ctrl ) {
Table table; TableRow tr; TableCell td;
// setup search results
table = new Table ( );
// add a row for each item
tr = new TableRow ( );
// display search results item
td = new TableCell ( );
td.Controls.Add ( buildImageLink ( ) );
tr.Controls.Add ( td );
...
table.Controls.Add ( tr );
IParserAccessor parser = ( ( IParserAccessor ) ( ctrl ) );
parser.AddParsedSubObject ( table );
}
private Control buildImageLink ( ) {
HyperLink ctrl = new HyperLink ( );
ctrl.ID = "asinImgLink";
IParserAccessor parser = ( ( IParserAccessor ) ( ctrl ) );
parser.AddParsedSubObject ( buildImage ( ) );
return ctrl;
}
private Control buildImage ( ) {
Image ctrl = new Image ( );
ctrl.ID = "asinImg";
ctrl.Border = 0;
return ctrl;
}
Show me
Akin to <asp:Image> controls declared at design time, the ImageUrl of dynamically generated images often is derived from a data source. In the case above, databinding is done via the ItemDataBound event handler of the DataList. Below shows a snippet of that code.
void setBinding ( Object src, DataListItemEventArgs e ) {
// handles the onItemDataBound event of the search results datalist
if ( e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem ) {
// set reference to current data record
DataRowView rowView = ( DataRowView ) e.Item.DataItem;
...
// get and set images
string imageUrl = ConfigurationManager.ConnectionStrings [ "imagespath" ] +
rowView [ "Asin" ] + ".01.TZZZZZZZ.jpg";
...
Image asinImg = ( Image ) e.Item.FindControl ( "asinImg" );
asinImg.ImageUrl = imageUrl;
asinImg.Attributes [ "onMouseOver" ] = "status='" +
rowView [ "Catalog" ] + " : " + product + "';return true";
...
}
}
}
Image Members