Thursday, February 10, 2011


Introduction:-In this article i will show you how to insert images in database and retrieve data from database in images.
Implementation:- In this article firstly i will convert the data in binary format and store them in database  and  for retrieve the information from database a take a generic handler it is mainly used for converting binary data.
Now below i am giving database script you can copy and run it in your sqlserver.   The name of the table is picture i take three column.
       1.Pid    int autoincreament.
2.Pname Varchar(50)
3.Pimage Image

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Picture]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[images](
      [Pid] [int] IDENTITY(1,1) NOT NULL,
      [Pname] [varchar](50) NULL,
      [Pimage] [image] NULL,
 CONSTRAINT [PK_images] PRIMARY KEY CLUSTERED
(
      [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END

Now i am giving source code for Default.aspx Page.Copy and Paste it in your Default.aspx page.
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        &nbsp;<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:FileUpload ID="FileUpload1" runat="server" /><br />
        <br />
        <asp:Button ID="Upload" runat="server" OnClick="Upload_Click"
            Text="Upload" Height="26px" /><br />
        <br />
        <asp:Label ID="lblMessage" runat="server"></asp:Label><br />
        <br />
        <br />
<asp:GridView ID="GridView1" runat="server"
              AutoGenerateColumns="False" DataKeyNames="ID"
              DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="PID" HeaderText="ID"
                InsertVisible="False" ReadOnly="True"
                               SortExpression="PID" />
<asp:BoundField DataField="PName" HeaderText="ImageName"
                               SortExpression="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server"  Height="100px"
 Width="100px"           ImageUrl='<%# "Handler.ashx?ID=" + Eval("PID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [PID], [PName], [PImage]
              FROM [Picture]"></asp:SqlDataSource>
   
    </div>
    </form>
</body>
</html>

Below i am giving Default.aspx.cs code:-
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection cn = new SqlConnection();
    protected void Page_Load(object sender, EventArgs e)
    {
 
            cn.ConnectionString = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;

    }
    protected void Upload_Click(object sender, EventArgs e)
    {
        string strImageName = TextBox1.Text.ToString();
        if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
        {
            byte[] imgSize = new byte[FileUpload1.PostedFile.ContentLength];
            HttpPostedFile uploadedImage = FileUpload1.PostedFile;
            uploadedImage.InputStream.Read(imgSize, 0, (int)FileUpload1.PostedFile.ContentLength);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "INSERT INTO picture(pName,pImage) VALUES (@pName,@pImage)";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@pname", strImageName);
            cmd.Parameters.AddWithValue("@pimage", imageSize);
            con.Open();
            cmd.ExecuteNonQuery();
            GridView1.DataBind();
        }
    }
}

Now  i am giving handler.ashx page:---
<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;

public class Handler : IHttpHandler
{
   
    public void ProcessRequest (HttpContext context)
    {
        SqlConnection con = new SqlConnection();
        cn.ConnectionString = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;

     
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "Select pName,pImage from picture  where pID =@pID";
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Connection = cn;
        cmd.Parameters.AddWithValue("@pID", context.Request.QueryString["pID"]);
        cn.Open();
        SqlDataReader dReader = cmd.ExecuteReader();
        dReader.Read();
        context.Response.BinaryWrite((byte[])dReader["pImage"]);
        dReader.Close();
        cn.Close();
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

   

}          

Friday, February 4, 2011

How to do paging in GridView At Runtime

This is my First Article In this article i am explaining about the how to do paging in gridview At runtime.
I think it will be useful for you.
Introduction- in this article i am explaining about how to do paging in datalist at run time . i think it will very useful for any .net Developer. Firstly i will insert data in grid view.

Implementation-   create a website , add page named Paging.aspx. place  Two Textboxes ,fileuploader,gridview and a button.



Database Script- create a table in database named tb_paging. Here I am giving you to complete database script of the table tb_product. See below:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_product]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[tb_product](
      [pid] [int] IDENTITY(1,1) NOT NULL,
      [pname] [varchar](50) NULL,
      [pprice] [int] NULL,
      [pimage] [varchar](500) NULL,
 CONSTRAINT [PK_tb_product] PRIMARY KEY CLUSTERED
(
      [pid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END



Source Code for Paging.aspx page:-
Just copy and paste this code in your page:-
<div>
   
        <table class="style1">
            <tr>
                <td class="style2">
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    Name of Product</td>
                <td class="style3">
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    Price of Product</td>
                <td class="style3">
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    Select
                    Image</td>
                <td class="style3">
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" 
                        ErrorMessage="only jpg,gif,.wav,.jpeg file are supported" ValidationExpression="^.+(.jpg|.JPG|.gif|.GIF|.jpeg|JPEG)$"
                        ControlToValidate="FileUpload1"></asp:RegularExpressionValidator>
                    <asp:Button ID="Button1" runat="server" Text="insert" onclick="Button1_Click" />
                </td>
            </tr>
            <tr>
                <td class="style2">
                    <asp:Button ID="Button2" runat="server" Height="22px" onclick="Button2_Click"
                        Text="scanding" />
                </td>
                <td class="style3">
                    Select Paging Value</td>
            </tr>
            <tr>
                <td class="style2">
                    <asp:Button ID="Button3" runat="server" onclick="Button3_Click"
                        Text="Descanding" />
                </td>
                <td class="style3">
                    <asp:DropDownList ID="DropDownList1" runat="server">
                       
                        <asp:ListItem>1</asp:ListItem>
                        <asp:ListItem>2</asp:ListItem>
                        <asp:ListItem>3</asp:ListItem>
                        <asp:ListItem>4</asp:ListItem>
                        <asp:ListItem>5</asp:ListItem>
                        <asp:ListItem>6</asp:ListItem>
                        <asp:ListItem>7</asp:ListItem>
                        <asp:ListItem>8</asp:ListItem>
                    </asp:DropDownList>
                    <asp:Button ID="Button4" runat="server" onclick="Button4_Click" Text="OK" />
                </td>
            </tr>
            <tr>
                <td class="style2">
                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                        Height="300px" PageSize="1" Width="538px" AllowPaging="True"
                        onpageindexchanging="GridView1_PageIndexChanging" CellPadding="4"
                        ForeColor="#333333" GridLines="None">
                        <RowStyle BackColor="#E3EAEB" />
                    <Columns>
                    <asp:TemplateField HeaderText="Id">
                    <ItemTemplate>
                    <asp:Label ID="label1" runat="server" Text='<%#Eval("pid") %>'></asp:Label>
                    </ItemTemplate>
                   
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                    <asp:Label ID="label2" runat="server" Text='<%#Eval("pname") %>'></asp:Label>
                    </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Price">
                    <ItemTemplate>
                    <asp:Label ID="label3" runat="server" Text='<%#Eval("pprice") %>'></asp:Label>
            
                    </ItemTemplate></asp:TemplateField>
                <asp:TemplateField HeaderText="Picture">
               
                <ItemTemplate>
                 <img src='pics/<%#Eval("pimage") %>' style="height: 95px; width: 93px" />
                </ItemTemplate></asp:TemplateField>
                
                    </Columns>
               
                        <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
                        <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
                        <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                        <EditRowStyle BackColor="#7C6F57" />
                        <AlternatingRowStyle BackColor="White" />
               
                    </asp:GridView>
                </td>
                <td class="style3">
                    &nbsp;</td>
            </tr>
        </table>
   
    </div>



Code for Paging.aspx.cs page:-

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Data.SqlClient;