Monday 6 August 2012

How to create a simple Image Galary in asp.net with javascript


How to create a simple Image Galary in asp.net with JavaScript





First create table with id ,imgname and img where id is auto increment and primary key.


When we click on image with mouse pointer it will look like this bellow:-






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

<!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 id="Head1" runat="server">
    <title>Untitled Page</title>

    <%--<script src="simplegalary.js" type="text/javascript"></script>--%>
    <style type="text/css">
   
    .bgdiv
   
    {
          background-color:Gray;
        opacity:1;
        filter:Alpha(opacity=100);
        vertical-align:middle ;
        text-align :center ;
    }
  
   
   
    </style>

<script type="text/javascript">
   

    function divhideshow() {

        var backgrnd = document.getElementById("bgdiv");
        var backstyle=document.getElementById("bgdiv").style .display ;
        if (backstyle == "none") {

            document.getElementById("bgdiv").style.display = "block";
            document.getElementById("bgpnl").style.display = "block";
           

        }
        else {

            document.getElementById("bgdiv").style.display = "none";
            document.getElementById("bgpnl").style.display = "none";
       
        }

}
 // javascript function to chage image source     
        function changeimgsrc(ob) {
          
            try {
                dvWidth = 100;
                dvHeight = 100;
               
                var centerX, centerY; // Get the x and y coordinates of the center in output browser's window
                if (self.innerHeight) {
                    centerX = self.innerWidth;
                    centerY = self.innerHeight;
                  
                }
                else if (document.documentElement && document.documentElement.clientHeight) {
                    centerX = document.documentElement.clientWidth;
                    centerY = document.documentElement.clientHeight;
                 }
                else if (document.body) {
                    centerX = document.body.clientWidth;
                    centerY = document.body.clientHeight;
                  
                }
                var offsetLeft = (centerX - dvWidth) / 2;
                var offsetTop = (centerY - dvHeight) / 2;
                var ojbDiv = document.getElementById(divId);
                ojbDiv.style.position = 'absolute';
                ojbDiv.style.top = offsetTop + 'px';
                ojbDiv.style.left = offsetLeft + 'px';
                ojbDiv.style.display = "block";
            }
            catch (e) { }
            var backgrnd = document.getElementById("bgdiv");
            var backstyle = document.getElementById("bgdiv").style.display;
            if (backstyle == "none") {
                document.getElementById("bgdiv").style.display = "block";
                document.getElementById("bgpnl").style.display = "block";
                }
            else {

                document.getElementById("bgdiv").style.display = "none";
                document.getElementById("bgpnl").style.display = "none";
            }
            document.getElementById("divimg").src = document.getElementById(ob).src;
            document.getElementById("divimg").style.marginTop = (centerY - document.getElementById("divimg").height) - 100; +'px';
            document.getElementById("divimg").style.marginLeft = centerX / 2 - document.getElementById("divimg").width; +'px';
            document.getElementById("divimg").style.marginBottom = (centerY - document.getElementById("divimg").height) - 100 +'px';
            document.getElementById("divimg").style.marginRight = centerX  / 2 - document.getElementById("divimg").width +'px';
       } 
   </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table cellpadding="3px"  cellspacing="2px">
    <tr>
    <td>
        &nbsp;</td>
    <td>&nbsp;</td>
   
    </tr>
    <tr>
    <td><asp:Label ID="img" runat ="server" Text="Upload Image"/></td>
    <td>
    <asp:FileUpload ID ="imgupload" runat ="server" />
   
    </td>
    </tr>
    <tr>
    <td></td><td><asp:Button  ID ="btnupload" runat ="server" Text ="Upload Image"
            onclick="btnupload_Click" /></td>
    </tr>
   
    </table>
    </div>
    <div>
    <asp:DataList id="datalistimg" BorderColor="Violet" runat="server" 
            RepeatColumns="4"  DataKeyField="id"
            ondeletecommand="datalistimg_DeleteCommand"
           
            oneditcommand="datalistimg_EditCommand"
            onupdatecommand="datalistimg_UpdateCommand" oncancelcommand="datalistimg_CancelCommand"
            >
   
    <ItemTemplate  >
    <table>
    <tr>
    <td align="left" style="border: thin solid #008080; width: 50px;" width="140px"
            colspan="2">
   
 
             <img  src = "img/<%# Eval("img") %>"  id='img<%#Container.ItemIndex%>' 
            alt="img/<%# Eval("img") %>" width="140" height="100" onclick ="javascript:changeimgsrc('img<%#Container.ItemIndex%>')"  style="right: auto; left: auto" />
    <br />
    </td>
    </tr>
       
   
        <tr>
            <td align="center " style="border: thin solid #008080; width: 50px;">
                <asp:LinkButton ID="LinkButton1"  CommandArgument="<% Container.ItemIndex %>" Text="Edit" CommandName="Edit" runat ="server" /></td>
            <td align="center " style="border: thin solid #008080; width: 50px;"
                width="100px">
                <asp:LinkButton ID="rmvitem" runat="server" CommandName="Delete"
                    CommandArgument="<% Container.ItemIndex %>" Text="Remove" />
            </td>
        </tr>
   
    </table>
   
   
   
    </ItemTemplate>
   
    <EditItemStyle Width ="140px" Height ="100px" />
    <EditItemTemplate>



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

<asp:Button ID="update" Text="Update" CommandName="update" runat="server" />

<asp:Button ID="Cancle" Text="Cancle" CommandName="cancel" runat="server"  />

</EditItemTemplate>
   
    </asp:DataList>
    </div>
    <asp:Panel ID="bgpnl" runat ="server" style ="width :100%; height :100%;  top :5px; left :5px; position :absolute ; vertical-align:middle; vertical-align :middle ; text-align :center ; " >
    <div id="bgdiv"  class="bgdiv" 
             style ="width :100%; height :100%; display:none ; background-color:Gray; text-align:center;    top :0px; left :5px; vertical-align:middle; " >
            <a href = "javascript:divhideshow();" id ="imgclose"  style ="vertical-align:middle;">
            <img  id ="divimg"    style ="left :100px;" height="500px" width ="400px"  alt ="" src="#"  />
            </a>
           </div></asp:Panel>
    </form>
</body>
</html>




 //C# Code
    public static SqlConnection con;
    DataSet ds;
    SqlDataAdapter da;
    SqlCommand com;
    string constr = "Data Source=FWSI-C25\\SqlExpress;Initial Catalog=Employee;Integrated Security=True";
    string fn;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            bind();
        }
             
    }

    public void bind()
    {

        da = new SqlDataAdapter("select * from imgtable", constr);
        ds = new DataSet();
        da.Fill(ds);
        datalistimg.DataSource = ds.Tables[0];
        datalistimg.DataBind();
    }



    protected void btnupload_Click(object sender, EventArgs e)
    {
        if (imgupload.FileName.Length > 0)
        {
            con = new SqlConnection(constr);

            con.ConnectionString = constr;
            com = new SqlCommand();

            com.CommandText = "insert into imgtable values(@imgname,@img)";
            //txtimgname.Text = imgupload.FileName.Substring(0, imgupload.FileName.Length - 4).ToString();
            com.Parameters.AddWithValue("@imgname", imgupload.FileName.Substring(0, imgupload.FileName.Length - 3).ToString());
            com.Parameters.AddWithValue("@img", imgupload.FileName);

            con.Open();
            com.Connection = con;
            com.ExecuteNonQuery();
            imgupload.SaveAs(Server.MapPath("~/img/" + imgupload.FileName));
            bind();
        }
    }



    protected void datalistimg_DeleteCommand(object source, DataListCommandEventArgs e)
    {
        int id = Convert.ToInt32(datalistimg.DataKeys[e.Item.ItemIndex]);
        con = new SqlConnection(constr);

        con.ConnectionString = constr;
        com = new SqlCommand();

        com.CommandText = "delete from  imgtable where id=@id";
        //txtimgname.Text = imgupload.FileName.Substring(0, imgupload.FileName.Length - 4).ToString();
        com.Parameters.AddWithValue("@id", id);

        con.Open();
        com.Connection = con;
        com.ExecuteNonQuery();
        bind();
    }
    protected void datalistimg_EditCommand(object source, DataListCommandEventArgs e)
    {
        datalistimg.EditItemIndex = e.Item.ItemIndex;
        bind();
    }
    protected void datalistimg_UpdateCommand(object source, DataListCommandEventArgs e)
    {
        int id = Convert.ToInt32(datalistimg.DataKeys[e.Item.ItemIndex]);
        con = new SqlConnection(constr);
        com = new SqlCommand();

        com.Connection = con;
     
        com.CommandText = "select img from imgtable where id=@id";
        com.Parameters.AddWithValue("@id", id);

       
        con.Open();
        SqlDataReader dr = com.ExecuteReader();
        //txtimgname.Text = imgupload.FileName.Substring(0, imgupload.FileName.Length - 4).ToString();
        com.Parameters.AddWithValue("@id", id);
        if(dr.HasRows )
        {
            while (dr.Read())
            {
                 fn = dr[0].ToString();
            }
        DirectoryInfo dd = new DirectoryInfo(Server.MapPath ("~/img/"));

        FileInfo[] ff = dd.GetFiles();
           
        foreach (FileInfo f in ff)
        {
            if (f.Name == fn)
                f.Delete();
           
        }}
        //string img1 = datalistimg.DataKeys[e.Item.ItemIndex].ToString();
        con = new SqlConnection(constr);
        //int id = Convert.ToInt32(datalistimg.DataKeys[e.Item.ItemIndex]);

        com.Parameters.Clear();

        com.Connection = con;

        com.CommandText = "update imgtable set imgname=@imgname,img=@img where id=@id";
        //txtimgname.Text = imgupload.FileName.Substring(0, imgupload.FileName.Length - 4).ToString();
        com.Parameters.AddWithValue("@id", id);
        FileUpload f1 = (FileUpload)e.Item.FindControl("imgupload1");
        com.Parameters.AddWithValue("@imgname",f1.FileName.Substring(0, f1.FileName.Length - 4).ToString());
        com.Parameters.AddWithValue("@img", f1.FileName.ToString ());

        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
               
                con.Open ();

        com.ExecuteNonQuery();
        f1.SaveAs(Server.MapPath("~/img/" +f1.FileName));
        con.Close();

        datalistimg.EditItemIndex = -1;

        bind();
   }

    protected void datalistimg_CancelCommand(object source, DataListCommandEventArgs e)
    {
        datalistimg.EditItemIndex = -1;
        bind();
    }

0 comments: