Wednesday, 24 July 2013

How to Upload and Retrieve image or File from Database and bind image to Gridviw in ASsp.Net




Description:-

            
  In this Example we explain that how to Upload Image of File in database and Retrieve this File and Display it in Gridview.

In this Example we also Check only .jpg,.jpeg,.gif,.png image are Inserted only if other type of Image you Choose then the Message will appear only .jpg,.jpeg,.gif,.png image are allowed other type is not allowed.

we also provide user to Display Gridview Row details in Javascript Modalpopup when user move mouse on the Gridview Row.

Here is a code for Checking the Extention of the Image File are as follow


string fileExtension = Path.GetExtension(FileUpload1.FileName.ToString());

        fileExtension.ToLower();

        if (fileExtension != ".gif" && fileExtension != ".jpg" && fileExtension != ".jpeg" && fileExtension != ".png")
        {

            ClientScript.RegisterClientScriptBlock(this.GetType(), "ke", "<script>alert('only jpeg,jpg,png,gif photo is allowed');</script>");

            return;

        }

We also check for File like .doc,.docx are Inserted only if you choose other type of File then Message will be appear only .doc,.docx File are allowed other type is not Allowed.

Here is a code for Checking the Extention of the Word File are as follow

string file = Path.GetExtension(FileUpload2.FileName.ToString());

        fileExtension.ToLower();

        if (file != ".docx" && file != ".doc")
        {

            ClientScript.RegisterClientScriptBlock(this.GetType(), "ke", "<script>alert('only .Doc and .docx is allowed');</script>");

            return;

        }

this is the Image For Displaying Uploaded Image.





To Show Example of How to Upload File in MVC plz Click Here Upload File in MVC

to show Example of Export Gridview Data to PDF file Export Gridview Rows to PDF File

insert,update,delete in Modal Popup Modap Popup For CRUD operation


How to Upload Image only .jpg, .jpeg ,.doc ,.docx:-

Default5.aspx:-



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>



<!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">

<script type="text/javascript">



    function fun() {

       

        var s = document.getElementById("foo");

        if (s.style.display == 'none')

            s.style.display = 'block';

       }

       

    

 

</script>

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

   

        <asp:Label ID="Label1" runat="server" Text="name"></asp:Label>

   

    &nbsp;&nbsp;&nbsp;&nbsp;

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

        <br />

        <br />

        <asp:Label ID="Label2" runat="server" Text="bod"></asp:Label>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><img src="cal.png" alt="ss" width="30" height="30" onclick="fun()" />

                  

        <div id="foo" style="display:none; position:absolute; left:150px; top:90px; width:100px; height:100px" >

        <asp:Calendar ID="Calendar1"

            runat="server"  SelectionMode="DayWeekMonth"

                onselectionchanged="Calendar1_SelectionChanged" BackColor="#0066FF"

                onvisiblemonthchanged="Calendar1_VisibleMonthChanged">

            <DayStyle BackColor="#FF0066" />

            </asp:Calendar></div>

        <asp:CompareValidator ID="CompareValidator1" runat="server"

            ControlToValidate="TextBox2" ErrorMessage="only date is allowed."

            Operator="DataTypeCheck" Type="Date"></asp:CompareValidator>

        <br />

        <br />

        <asp:Label ID="Label3" runat="server" Text="photo"></asp:Label>

&nbsp;&nbsp;&nbsp;

        <asp:FileUpload ID="FileUpload1" runat="server" />

        <br />

        <br />

        <asp:Label ID="Label4" runat="server" Text="File"></asp:Label>

&nbsp;&nbsp;

        <asp:FileUpload ID="FileUpload2" runat="server" />

        <br />

        <br />

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add" />

&nbsp;&nbsp;&nbsp;

        <asp:Button ID="Button2" runat="server" CausesValidation="False"

            onclick="Button2_Click" Text="cancel" />

   

  

    </form>

</body>

</html>



Default5.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;

using System.IO;



public partial class Default5 : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {



    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        string fileExtension = Path.GetExtension(FileUpload1.FileName.ToString());

        fileExtension.ToLower();

        if (fileExtension != ".gif" && fileExtension != ".jpg" && fileExtension != ".jpeg" && fileExtension != ".png")

        {

            ClientScript.RegisterClientScriptBlock(this.GetType(), "ke", "<script>alert('only jpeg,jpg,png,gif photo is allowed');</script>");

            return;

        }

        string file = Path.GetExtension(FileUpload2.FileName.ToString());

        fileExtension.ToLower();

        if (file!= ".docx" && file != ".doc")

        {

            ClientScript.RegisterClientScriptBlock(this.GetType(), "ke", "<script>alert('only .Doc and .docx is allowed');</script>");

            return;

        }

        string con = @"Data Source=SQLDB;Initial Catalog=Demo;User ID=Demoh;Password=Demo1@";

        string serverPath = Server.MapPath(@"~/images/" + FileUpload1.FileName);

        FileUpload1.SaveAs(serverPath);

        string serverPath1 = Server.MapPath(@"~/File/" + FileUpload2.FileName);

        FileUpload2.SaveAs(serverPath1);



        string q = "insert into bio values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + FileUpload1.FileName + "','" + FileUpload2.FileName + "')";

        SqlConnection conn = new SqlConnection(con);



        SqlCommand cmd = new SqlCommand(q, conn);

       conn.Open();

        int i=cmd.ExecuteNonQuery();

        if (i > 0)

        {

            Response.Redirect("~/Default4.aspx");

        }

      



    }

    protected void Button2_Click(object sender, EventArgs e)

    {

        Response.Redirect("~/Default4.aspx");

    }

    protected void Calendar1_SelectionChanged(object sender, EventArgs e)

    {

        TextBox2.Text = Calendar1.SelectedDate.ToString("d");



    }

    protected void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e)

    {

        DateTime nextMonth = DateTime.Now.AddMonths(1);

        Calendar1.TodaysDate = nextMonth;

    }

}



How To Display Uploaded Image From database:-

Defaut4.aspx:-



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" EnableEventValidation="false" %>



<!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></title>

    <style type="text/css">


    .HiddenColumn
{
    display: none;
}

    </style>
    <script type="text/javascript">
        function OpenNewPage(strRowIndex) {
            window.open("SecondPage.aspx?id=" + strRowIndex, "New Window",

"toolbar=no,menubar=no,top=100,left=100,titlebar=no");
        }
       
        function shownext(event,a) {
           
            var grid = document.getElementById("<%= GridView1.ClientID %>");

            var id = grid.rows[event].cells[0].firstChild.nodeValue;
            var name = grid.rows[event].cells[1].firstChild.nodeValue;
            var bod = grid.rows[event].cells[2].firstChild.nodeValue;
            var p = grid.rows[event].cells[3].firstChild.nodeValue;


            document.getElementById("foo").innerHTML = "Id=" + id + "<br>Name=" + name + "<br>bod=" + bod + "<br>photo=" + '<img src="Z:/kiit/homework/' + a + '" alt="some alt text" width=50 height=50 />';
           
        }
        function confirmSubmit() {

      var agree=confirm("Do you really want to Delete Record?");

      if (agree)

       return true ;

      else

       return false ;


}


function crs() {

    document.getElementById("foo").style.display = 'block';
var f = document.getElementById("foo");

f.style.posLeft = event.clientX - 10;
f.style.posTop = event.clientY - 10;


}
function hide() {
    document.getElementById("foo").style.display = 'none';
   
}
      
    </script>
   

</head>
<body >
    <form id="form1" runat="server">
    <div>
       
       
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px"
            CellPadding="4" 
            DataKeyNames="photo" onrowdeleting="GridView1_RowDeleting"
            onrowcancelingedit="GridView1_RowCancelingEdit"
            onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
             Font-Names = "Arial"

    Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"

    HeaderStyle-BackColor = "green" AllowPaging ="true" onrowdatabound="GridView1_RowDataBound1" 

    >
           
            <RowStyle BackColor="White" ForeColor="#003399" />
            <Columns>
            <asp:TemplateField HeaderImageUrl="~/chk.jpeg">
            <ItemTemplate>
                <asp:CheckBox ID="CheckBox1" runat="server" />
            </ItemTemplate>
            </asp:TemplateField>
                <asp:BoundField DataField="id" HeaderText="ID" SortExpression="id" />
                <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
                <asp:BoundField DataField="bod" HeaderText="bod" SortExpression="name" />
               
               <asp:TemplateField HeaderText="photo" >
               
                <ItemTemplate>
               
                    <asp:Image ID="Image1" runat="server"  AlternateText="abc" Width="80" Height="80" />
                     </ItemTemplate>
               
                </asp:TemplateField>
               
          
            <asp:BoundField DataField="word" HeaderText="File" SortExpression="file" />
               
            <asp:TemplateField>
                <ItemTemplate>
            <asp:ImageButton ID="ImageButton2" ImageUrl="~/images/del.jpeg" runat="server" Width="80" Height="80" CommandName="Delete" ToolTip="Delete Record" OnClientClick="return confirmSubmit()"/>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
            <ItemTemplate>
            <asp:ImageButton ID="ImageButton3" ImageUrl="~/images/edit.jpeg" CommandName="Update" Width="80" Height="80" runat="server" ToolTip= "Update Record" />
            </ItemTemplate>
            </asp:TemplateField>
           
            <asp:TemplateField>
            <ItemTemplate>
            <img src="help.jpeg" id="fooo" alt="dd" onmouseover="crs();" onmouseout="hide();" height="80" width="80" />                  

  
                                    

            </ItemTemplate>
            </asp:TemplateField>
                       </Columns>
           
            <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
            <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
            <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
            <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
            
        </asp:GridView>
       
        <asp:ImageButton ID="ImageButton3" runat="server" ImageUrl="~/add.jpeg" Height="50" Width="60" OnClick="Button1_click" ToolTip="add record" />     
            <asp:ImageButton ID="ImageButton4" runat="server" ImageUrl="~/del.jpeg"  OnClick="delclick" Height="50" Width="60"/>
           <asp:ImageButton ID="ImageButton5" runat="server" ImageUrl="~/WordImage.jpg" OnClick="wordclick" Height="50" Width="60"/>
          
        
           <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
          
        
           </div>
   
    <div id="foo" style="position:absolute;top:10;left:10;height:20;width:20;background-color:red; overflow:scroll; border-style:solid; font-size:large;"></div>
   
    </form>
   
</body>
</html>



Default4.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;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.IO;

public partial class Default4 : System.Web.UI.Page
{
    string z = null;
    DropDownList d1, d2, d3;
    Image i;
    //List<string> li = new List<string>();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            grid();
        }

    }
    protected void grid()
    {
        Image i,k;
        Label j;

        DataSet ds = new DataSet();

        string con = @"Data Source=SQLDB;Initial Catalog=Demo;User ID=Demoh;Password=Demo1@";

        string q = "select * from bio";

        SqlConnection conn = new SqlConnection(con);

        SqlCommand cmd = new SqlCommand(q, conn);



        SqlDataAdapter sa = new SqlDataAdapter();
        conn.Open();
        cmd.ExecuteNonQuery();
        sa.SelectCommand = cmd;
        sa.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();

        foreach (GridViewRow grdRow in GridView1.Rows)
        {

            i = (Image)(GridView1.Rows[grdRow.RowIndex].Cells[3].FindControl("Image1"));
            string a = GridView1.DataKeys[grdRow.RowIndex].Value.ToString();
            i.ImageUrl ="~/images/"+ a.ToString();
            /*j = (Label)(GridView1.Rows[grdRow.RowIndex].Cells[5].FindControl("Label2"));
            string b = GridView1.Rows[grdRow.RowIndex].Cells[5].Text;
            j.Text = b.ToString();
            j.DataBind();*/
            i.DataBind();
            //Label1.Text = b.ToString();
            //Label1.Text = Server.MapPath(@"~/images/" + a);
          
        }

       

    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        string con = @"Data Source=SQLDB;Initial Catalog=Demo;User ID=Demoh;Password=Demo1@";
        //z=GridView1.Rows[e.RowIndex].Cells[0].Text;
        String i = GridView1.Rows[e.RowIndex].Cells[1].Text;
        // string id1 = GridView1.Rows[i+1].Cells[0].Text.ToString();

        string q = "delete from bio where id = " + i.ToString();
        SqlConnection conn = new SqlConnection(con);

        SqlCommand cmd = new SqlCommand(q, conn);
        conn.Open();

        cmd.ExecuteNonQuery();
        grid();



    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        String id = GridView1.Rows[e.RowIndex].Cells[1].Text;
        String nm = GridView1.Rows[e.RowIndex].Cells[2].Text;
        String bd = GridView1.Rows[e.RowIndex].Cells[3].Text;
        String pht = GridView1.Rows[e.RowIndex].Cells[4].Text;

        Response.Redirect("Default6.aspx?id=" + id + "&name=" + nm + "&bod=" + bd + "&photo=" + pht);

        grid();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;

        grid();

    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;

        grid();
    }
    protected void Button1_click(object sender, ImageClickEventArgs e)
    {
        ImageButton3.PostBackUrl = "~/Default5.aspx";
        grid();
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            e.Row.Attributes.Add("onclick", ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex));
        }
    }

    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        foreach (GridViewRow row in GridView1.Rows)
        {

            int j = row.RowIndex + 1;

            i = (Image)(GridView1.Rows[row.RowIndex].Cells[3].FindControl("Image1"));
            string a = GridView1.DataKeys[row.RowIndex].Value.ToString();
            row.Attributes["onmouseover"] = "javascript:shownext('" + j + "','" + a + "')";

        }
        base.Render(writer);
    }
    protected void delclick(object sender, ImageClickEventArgs e)
    {
        foreach (GridViewRow grdRow in GridView1.Rows)
        {

            CheckBox c = (CheckBox)(GridView1.Rows[grdRow.RowIndex].Cells[0].FindControl("CheckBox1"));
            string a = GridView1.Rows[grdRow.RowIndex].Cells[1].Text;
            if (c.Checked)
            {
                string con = @"Data Source=SQLDB;Initial Catalog=Demo;User ID=Demoh;Password=Demo1@";


                string q = "delete from bio where id = " + a.ToString();
                SqlConnection conn = new SqlConnection(con);

                SqlCommand cmd = new SqlCommand(q, conn);
                conn.Open();

                cmd.ExecuteNonQuery();




            }

          

        }
        grid();
    }
    protected void wordclick(object sender, ImageClickEventArgs e)
    {
        GridView1.AllowPaging = false;
        grid();
        GridView1.DataBind();
        foreach (GridViewRow grdRow in GridView1.Rows)
        {
            i = (Image)(GridView1.Rows[grdRow.RowIndex].Cells[4].FindControl("Image1"));
            string a = GridView1.DataKeys[grdRow.RowIndex].Value.ToString();

            HtmlImage i1 = (HtmlImage)(GridView1.Rows[grdRow.RowIndex].Cells[7].FindControl("fooo"));
            ImageButton b = (ImageButton)(GridView1.Rows[grdRow.RowIndex].Cells[5].FindControl("ImageButton2"));
            ImageButton c = (ImageButton)(GridView1.Rows[grdRow.RowIndex].Cells[6].FindControl("ImageButton3"));
            b.ImageUrl = "~/images/del.jpeg";
            c.ImageUrl = "~/images/edit.jpeg";
            i.ImageUrl = Server.MapPath(@"~/images/" + a);
           
            i.DataBind();
        }
        Response.ClearContent();
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.doc"));
        Response.Charset = "";
        Response.ContentType = "application/ms-word";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GridView1.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
}




   


    public override void VerifyRenderingInServerForm(Control control)
    {

        /* Verifies that the control is rendered */

    }
    protected void GridView1_RowDataBound(GridViewRowEventArgs e)
    {
        e.Row.Attributes.Add("onclick", "OpenNewPage('" + e.Row.RowIndex + "')");
    }

    protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            System.Data.DataRowView drv = e.Row.DataItem as System.Data.DataRowView;
            e.Row.Attributes.Add("ondblclick", String.Format("window.location='Default7.aspx?id={0}'", drv["id"]));
        }

    }
}





0 comments:

Post a Comment