DataList Image Binding: Hai Folks, In this posting I’m going to explain how to insert image into database and how to bind the inserted image into datalist control. Let us see in detail. First of all we have to create the database with the following fields.
Here the Prod_Img field only goes to store the specified/selected image in a binary format. After creating these database table designs our next step is to create the Front-End to insert the image details into database. Create the following Front-End design. Name the webpage name is “imginsert.aspx”.
Imginsert.aspx.cs:
Add the namespace for database connectivity.
using System.Data.SqlClient;
using System.Data;
protected void Page_Load(object sender, EventArgs e)
{
//Random Number Generation for image_ID
Random rn = new Random();
//this Label1 is used to bind the generated random number.
Label1.Text = "PRD" + rn.Next(10000, 90000);
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
// SqlCommand cmd = new SqlCommand();
con.ConnectionString = "Data Source=.;Initial Catalog=DB_Name;uid=sa;password=hi";
try
{
FileUpload img = (FileUpload)FileUpload1;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = FileUpload1.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the employee name and image into db
con.Open();
string sql = "INSERT INTO products(Prod_Id,Prod_Name,Prod_Desc,Prod_Img,Prod_Cost) VALUES(@pid,@pname,@pdesc,@pimg,@pcost) SELECT @@IDENTITY";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("@pid",Label1.Text); cmd.Parameters.AddWithValue("@pname",TextBox1.Text); cmd.Parameters.AddWithValue("@pdesc",TextBox2 .Text);
cmd.Parameters.AddWithValue("@pimg", imgByte); cmd.Parameters.AddWithValue("@pcost",TextBox3.Text);
//int id = Convert.ToInt32(cmd.ExecuteScalar());
//lblResult.Text = String.Format("Employee ID is {0}", id);
cmd.ExecuteNonQuery();
}
catch
{
Label2.Text = "There was an error";
}
finally
{
con.Close();
}
Next we are going to design the datalist.aspx page for binding the inserted image details in datalist. To do this we have to design the ItemTemplate for datalist.
<asp:DataList ID="DataList1" runat="server" BackColor="#666666" RepeatColumns="2">
<AlternatingItemStyle BackColor="#993366" />
<ItemStyle BackColor="#990099" />
<ItemTemplate>
<table class="style1"
style="font-size: 20px; font-weight: lighter; color: #000000; font-family: 'Bookman Old Style'">
<tr>
<td class="style2">
Product_ID:</td>
<td class="style3">
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Prod_ID") %>'></asp:Label>
</td>
</tr>
<tr>
<td class="style2">
Product_Name</td>
<td class="style3">
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Prod_Name") %>'></asp:Label>
</td>
</tr>
<tr>
<td class="style2">
Product_Description:</td>
<td class="style3">
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Prod_Desc") %>'></asp:Label>
</td>
</tr>
<tr>
<td class="style2">
Product_Cost</td>
<td class="style3">
<asp:Label ID="Label4" runat="server" Text='<%# Eval("Prod_Cost") %>'></asp:Label>
</td>
</tr>
<tr>
<td class="style2">
Product_Image:</td>
<td class="style3">
<asp:ImageButton ID="ImageButton1" runat="server" Height="159px" ImageUrl='<%# "img_handler.ashx?Prod_ID="+ Eval("Prod_ID") %>'
Width="197px" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
Datalist.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class datalist : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.;Initial Catalog=DB_Name;uid=sa;password=hi";
con.Open();
SqlCommand command = new SqlCommand("SELECT Prod_ID,Prod_Name,Prod_Desc,Prod_Img,Prod_cost from products", con);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
DataList1 .DataSource = dt; DataList1.DataBind();
//gvImages.Attributes.Add("bordercolor", "black");
con.Close();
}
}
}
Now we are going to add handler for binding images to datalist.
Choose website ->add new item->Generic Handler and name the handler is “img_handler.ashx” .
<%@ WebHandler Language="C#" Class="img_handler" %>;
using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
public class img_handler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
string strcon = "Data Source=.;Initial Catalog=DB_Name;uid=sa;password=hi";
string imageid = context.Request.QueryString["Prod_ID"];
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand command = new SqlCommand("select Prod_Img from products where Prod_ID='"+imageid+"'", connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
public bool IsReusable { get { return false; } }
}
Output: