If your intent is just to display data and images, then you may use a
Repeater
control as suggested to have more flexibility in terms of layout formatting. You could also use
DataList
since it provides properties like
RepeatLayout
and
RepeatDirection
that you can set.
Here's a quick example with
DataList
:
<asp:DataList ID="DataList1" runat="server" RepeatColumns="2" RepeatDirection="Vertical">
<ItemTemplate>
<table>
<tr>
<td><asp:Image ID="imgProduct" runat="server" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "ProductImage") %>' style="width:100px; height:100px;" /></td>
<td>
<asp:Label ID="lblProduct" Text='<%# DataBinder.Eval(Container.DataItem, "ProductName") %>' runat="server" />
<br />
<asp:Label ID="lblPrice" Text='<%# DataBinder.Eval(Container.DataItem, "Price") %>' runat="server" />
<br />
<asp:TextBox ID="txtQty" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
As you can see, there's really no fancy about the mark-up above. It just contain a
DataList
control with
Image
,
TextBox
and
Label
controls defined within it. You may also noticed that each control are binded with the fields that we want to display. Now let’s go ahead and populate the
DataList
with a sample data. Here’s the code behind part below:
using System;
using System.Data;
namespace WebAppDemo {
public partial class Repeater : System.Web.UI.Page {
private DataTable GetSampleData() {
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("ID", typeof(string)));
dt.Columns.Add(new DataColumn("ProductImage", typeof(string)));
dt.Columns.Add(new DataColumn("ProductName", typeof(string)));
dt.Columns.Add(new DataColumn("Price", typeof(string)));
dr = dt.NewRow();
dr["ID"] = 1;
dr["ProductName"] = "Product 1";
dr["ProductImage"] = "~/Images/Image1.jpg";
dr["Price"] = "100";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = 2;
dr["ProductName"] = "Product 2";
dr["ProductImage"] = "~/Images/Image2.jpg";
dr["Price"] = "200";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = 3;
dr["ProductName"] = "Product 3";
dr["ProductImage"] = "~/Images/Image3.jpg";
dr["Price"] = "50";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = 3;
dr["ProductName"] = "Product 4";
dr["ProductImage"] = "~/Images/Image4.jpg";
dr["Price"] = "500";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = 3;
dr["ProductName"] = "Product 5";
dr["ProductImage"] = "~/Images/Image5.jpg";
dr["Price"] = "70";
dt.Rows.Add(dr);
return dt;
}
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
DataList1.DataSource = GetSampleData();
DataList1.DataBind();
}
}
}
}
That's it.
For working with images, check this post:
ASP.NET WebForms: Uploading, Validating And Displaying of Image