Click here to Skip to main content
15,885,767 members
Articles / Web Development / HTML

How to Add/Delete/Edit/Update Image, and Save to SQL Database Table, and also how to create a menu like an Outlook with faded in slide show

Rate me:
Please Sign up or sign in to vote.
3.88/5 (4 votes)
29 Oct 2011CPOL4 min read 104.6K   5.3K   33   8
Demonstrates how to Add/Delete/Edit/Update image, and save to SQL database table, and also how to create a menu like an Outlook with faded in slide show

How this Project (Article) Was Implemented?

Make a directory C:\AlmojeArticle2.

Copy zip source code file in your computer at: C:\AlmojeArticle2 then unzip it…

image002.jpg

The project location is at C:\ AlmojeArticle2\Article2 as shown below:

image003.jpg

Click on CreateUserSetupDB subdirectory.

image004.jpg

Double click on UserSetup file (SQL script file) as shown above.

(Note that there should be an MS-SQL Management Studio installed in your computer - either version 2005 or later version.)

image005.jpg

Then double click on Execute (SQL Script as shown above).

The SQL Management Studio will create a database as shown in the screenshot below:

image006.jpg

If you open the SQL Management Studio, the script should be automatically attached. Check if such database attached as shown below appeared:

 image007.jpg

Double click on solution.

image008.jpg

image009.jpg

Right click on Welcome.aspx. Set as Start Page, then press F5.

The application will run as shown below:

image010.jpg

Click on the menu User Account as shown above.

image011.jpg

Click Add New button as shown above to add record…

image012.jpg

Fill-In text boxes the Click Save.

The system will save record in database table and display information in grid as shown below.

image013.jpg

Click on Edit Icon.

Browse folder in C:\AlmojeArticle2\Article2\Sample Images.

Pick up one image file.

image014.jpg

Click on Save button

The system will update the image in database table the display in grid as shown below:

image015.jpg

image016.jpg

Add another record(s) with image.

image017.jpg

Click on back and see the auto slide show.

You could add as many records as you can. The images are saved in the database table not in the virtual directory…

Introduction

This article is an updated version of my previous article at DatabaseToGridview.aspx.

This article will demonstrate the technical usage on how to Add/Delete/Edit/Update image, and to save to SQL database table, and also how to create a menu like an Outlook with faded in slide show.

The Database

As I mentioned earlier, from my previous article reasons:

Why should we use a database and not just have the images within a virtual folder under the main ASP.NET folder? Well, there are several reasons why it might be good to store images in a database.

Please see reason here.

So what does the database [UsersInfo] look like?

It simply contains one table called User which can be setup using the following script (This SQL Script is a content within the object created at the top of this article)

SQL
USE [master]
GO
/****** Object:  Database [UsersInfo]    Script Date: 10/14/2011 08:49:36 ******/
CREATE DATABASE [UsersInfo] ON  PRIMARY 
( NAME = N'UserDB', FILENAME = N'C:\AlmojeArticle2\Article2\App_Data\UsersInfo.mdf' , 
SIZE = 2048KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'UserDB_log', _
	FILENAME = N'C:\AlmojeArticle2\Article2\App_Data\UsersInfo_log.ldf' , 
SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO
ALTER DATABASE [UsersInfo] SET COMPATIBILITY_LEVEL = 90
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [UsersInfo].[dbo].[sp_fulltext_database] @action = 'disable'
end
GO
ALTER DATABASE [UsersInfo] SET ANSI_NULL_DEFAULT OFF
GO
ALTER DATABASE [UsersInfo] SET ANSI_NULLS OFF
GO
ALTER DATABASE [UsersInfo] SET ANSI_PADDING OFF
GO
ALTER DATABASE [UsersInfo] SET ANSI_WARNINGS OFF
GO
ALTER DATABASE [UsersInfo] SET ARITHABORT OFF
GO
ALTER DATABASE [UsersInfo] SET AUTO_CLOSE ON
GO
ALTER DATABASE [UsersInfo] SET AUTO_CREATE_STATISTICS ON
GO
ALTER DATABASE [UsersInfo] SET AUTO_SHRINK OFF
GO
ALTER DATABASE [UsersInfo] SET AUTO_UPDATE_STATISTICS ON
GO
ALTER DATABASE [UsersInfo] SET CURSOR_CLOSE_ON_COMMIT OFF
GO
ALTER DATABASE [UsersInfo] SET CURSOR_DEFAULT  GLOBAL
GO
ALTER DATABASE [UsersInfo] SET CONCAT_NULL_YIELDS_NULL OFF
GO
ALTER DATABASE [UsersInfo] SET NUMERIC_ROUNDABORT OFF
GO
ALTER DATABASE [UsersInfo] SET QUOTED_IDENTIFIER OFF
GO
ALTER DATABASE [UsersInfo] SET RECURSIVE_TRIGGERS OFF
GO
ALTER DATABASE [UsersInfo] SET  DISABLE_BROKER
GO
ALTER DATABASE [UsersInfo] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
GO
ALTER DATABASE [UsersInfo] SET DATE_CORRELATION_OPTIMIZATION OFF
GO
ALTER DATABASE [UsersInfo] SET TRUSTWORTHY OFF
GO
ALTER DATABASE [UsersInfo] SET ALLOW_SNAPSHOT_ISOLATION OFF
GO
ALTER DATABASE [UsersInfo] SET PARAMETERIZATION SIMPLE
GO
ALTER DATABASE [UsersInfo] SET READ_COMMITTED_SNAPSHOT OFF
GO
ALTER DATABASE [UsersInfo] SET HONOR_BROKER_PRIORITY OFF
GO
ALTER DATABASE [UsersInfo] SET  READ_WRITE
GO
ALTER DATABASE [UsersInfo] SET RECOVERY FULL
GO
ALTER DATABASE [UsersInfo] SET  MULTI_USER
GO
ALTER DATABASE [UsersInfo] SET PAGE_VERIFY CHECKSUM
GO
ALTER DATABASE [UsersInfo] SET DB_CHAINING OFF
GO
USE [UsersInfo]
GO
/****** Object:  Table [dbo].[User]    Script Date: 10/14/2011 08:49:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[User](
      [UserID] [int] IDENTITY(1,1) NOT NULL,
      [Username] [varchar](255) NOT NULL,
      [Password] [varchar](max) NOT NULL,
      [LastName] [varchar](255) NULL,
      [FirstName] [varchar](255) NULL,
      [MiddleName] [varchar](255) NULL,
      [WorksiteCode] [varchar](50) NOT NULL,
      [AccessLevel] [int] NOT NULL,
      [Active] [varchar](5) NOT NULL,
      [DateCreated] [datetime] NULL,
      [DateUpdated] [datetime] NULL,
      [Worksitedesc] [varchar](50) NULL,
      [Picture] [varbinary](max) NULL,
      [ImageFull] [varbinary](max) NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
      [UserID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, _
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO

So How do I make a Menu like an Outlook?

Let's have a look at the client code and on its code behind that I’d made, they are quite easy, in fact I think the comments code pretty much explain them in enough detail. So I just picked up some important line of code and won't bore you with any more explanatory words, as it’s clear, isn't it?

So here is the client code (js\OutlookMenu.aspx).

CSS
<link rel="Stylesheet" type="text/css" href="css/XPStyle.css" />
<style type="text/css">
    .marquee:
    {
        width: auto;
        height: auto;
        color: #CC9900;
    }
    .verticaltext
    {
        font: bold 10px Arial;
        position: absolute;
        right: 3px;
        top: 20px;
        width: 15px;
        writing-mode: tb-rl;
    }
</style>
<script type="text/javascript" src="js/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="js/AlgemShow.js"></script>
<script language="JavaScript" src="js/crossbrowser.js" type="text/javascript"> </script>
<script language="JavaScript" src="js/outlook.js" type="text/javascript"></

I had created a CSS code (css/XPStyle.css) for my look and fill page customization and am referencing it, and also an additional CSS for scrolling of image as shown above. I also included four JavaScripts from Dynamic Drive to perform slide show images.

So here it is (client code) …

HTML
<td width="14%">
   <asp:Literal ID="myMenu" runat="server" OnPreRender="myMenu_PreRender" Text="">
   </asp:Literal>
</td>
<td>
   <div id="fadeshow1">
       <asp:Literal ID="Literal1" runat="server" Text=""></asp:Literal>
   </div>
</td>

In the above code, I define a table definition width="14%" for my menu as asp:Literal with a unique ID="myMenu". This hold the menus selection. I also defined a division to hold for my auto slide show with a unique div id="fadeshow1" as asp:Literal.

And here is the code behind those implements above…

C#
protected void Page_PreRender(object sender, EventArgs e)
{
    try
    {
        // Call a function to return a literal text then register on page  
        string fadeshow1 = AlgemShow("Show", "*.jpg", 
        "always", "fadeshow1", "340", "340", "peekaboo", "");
        Page.ClientScript.RegisterStartupScript(GetType(), "Startup", fadeshow1, false);
    }
    catch (Exception)
    {
    }
    // Here I include a hidden text field to hold an access level 
    // if ever login page should provide.  
    if (this.hfAccessLvl.Value == string.Empty)
    {
        this.hfAccessLvl.Value = "9";  // Since I have no login page,
        		//I set Administrator rights to 9 for demo purposes.
    }      
    //string menus = string.Empty;
    try
    {
        string appsPath = Server.MapPath("./");
        //Call the function AlMenu passing target outlook file menu, 
        //and the access level of 
        //user with its target width and height of the menu page.
        this.myMenu.Text = AlMenu("js/OutlookMenu.aspx?accesLevel=" + 
        this.hfAccessLvl.Value, "no", "460px", "100");
    }
    catch (Exception)
    {
 
    }
}
 
protected string AlMenu
	(string outlookFile, string isScrolling, string height, string width)
{
   //Purpose wrapped the C# code to form an html code (for Outlook like menu)...
    StringBuilder sb = new StringBuilder();
    sb.Append("<iframe id=\"OutLookMenu\"");
    sb.Append("src='" + outlookFile + "' ");
    sb.Append("name=\"Links\" scrolling='" + isScrolling + "' height='" + height + "', ");
    sb.Append("width='" + width + "%'></iframe>'");
    return sb.ToString();
}
public string AlgemShow(string target, string fileExt, string toggle,
           string ids, string heigth, string weidth, string descreveals, string message)
{
   // Author: Algem G Mojedo
   // Date: 2-22-2011  
   //Purpose Get file name of images in a target virtual drive…
   //Wrapped the C# code to form an html script code (for slide show)...
   // Target drive image show is at: C:\AlmojeArticle2\Article2\Show
   bool useFileName = false;
   if (message == string.Empty) 
   {
       useFileName = true;
   }
   string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + target;
   string targets = path + "\\";
   string[] files = Directory.GetFiles(targets, fileExt);
   DirectoryInfo infoDir = new DirectoryInfo(targets);
   StringBuilder sb = new StringBuilder();
   sb
   .Append("<script type=\"text/javascript\"> ")
   .Append("var gallary=new AlgemShow({ ")
   .Append("wrapperid: ")
   .Append("\"").Append(ids).Append("\", ")
   .Append("dimensions: [" + heigth + "," + weidth + "], ")
   .Append("imagearray: [");
   
        foreach (var item in files)
        {
            string fileName = Path.GetFileNameWithoutExtension(item);
            string messages = item.Replace(targets, "");
            string itemValue = target + "\\\\" + messages;
            if (useFileName)
            {
                message = fileName;
            }
            sb.Append("[").Append("\"").Append(itemValue).Append("\",").Append("\"\",\"")
                .Append("\",\"").Append(message).Append("\"], ");
        }
        string arr = sb.ToString().Substring(0, sb.ToString().LastIndexOf(","));
        StringBuilder sb2 = new StringBuilder();
        sb2.Append(arr);
        sb2.Append("], ")
       .Append("displaymode: {type:'auto', pause:2500, cycles:0, wraparound:true}, ")
       .Append("persist: false, ")
       .Append("fadeduration: 500, ")
       .Append("descreveal: \"").Append(descreveals).Append("\", ");
        if (toggle == string.Empty)
        {
            sb2.Append("togglerid: \"\" ");
        }
        else
        {
            sb2.Append("togglerid: \"").Append(toggle).Append("\" ");
        }
        sb2.Append("}) ")
        .Append("</script>");
        string cmd = sb2.ToString();
        return cmd;
    }

The code behind for DataGridView on Add/Delete/Expand image was in my previous article at DatabaseToGridview.aspx.

And here is the client code for editing on DataGridView. I should outline the important code lines because some are quite easy:

So here it is…

ASP.NET
<%@ Register Src="~/UsersControl/EditUserAcct.ascx" 
		TagName="EditUserAcct" TagPrefix="uc4" %>

The above code is to register the Users Control on page:

ASP.NET
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Edit">
  <ItemTemplate>
     <asp:ImageButton ID="gImgBtnEdit" runat="server" ToolTip="Edit" 
     ImageUrl="~/Images/btn_edit.gif" OnClick="gImgBtnEdit_Click" />
  </ItemTemplate>
  <ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>

The above code defines the template field for Image button click.

ASP.NET
<cc1:ModalPopupExtender runat="server" ID="mpeEditUserAcct" 
	TargetControlID="hfPopEditAcct"
     PopupControlID="pnlEditUserAcct" BackgroundCssClass="AlgemBackground" 
	BehaviorID="mpeBehavior4"
     DropShadow="false" PopupDragHandleControlID="pnlEditUserAcct">
 </cc1:ModalPopupExtender>
 <asp:Panel runat="server" ID="pnlEditUserAcct" Style="display: none; 
	background-color: White;" Width="70%">
     <uc4:EditUserAcct runat="server" ID="ucEditUserAcct" />
 </asp:Panel>
<asp:Button runat="server" ID="hfPopEditAcct" Style="display: none" />

The above code is a definition of the popup modal (Users Control).

C#
protected void gImgBtnEdit_Click(object sender, EventArgs e)
{    
    ImageButton iBtnEdit = sender as ImageButton;
    GridViewRow row = (GridViewRow)iBtnEdit.NamingContainer;
    User user = new User();
    // Get the value of column cell and store to user defined class
    user.UserID = Tools.Tools.IifInt(row.Cells[2].Text);
 
    user.Username = Tools.Tools.IifStr(row.Cells[3].Text);
    user.Password = Tools.Tools.IifStr(row.Cells[4].Text);
    user.LastName = Tools.Tools.IifStr(row.Cells[5].Text);
    user.FirstName = Tools.Tools.IifStr(row.Cells[6].Text);
    user.MiddleName = Tools.Tools.IifStr(row.Cells[7].Text);
    user.WorksiteCode = Tools.Tools.IifStr(row.Cells[8].Text);
    user.AccessLevel = Tools.Tools.IifInt(row.Cells[9].Text);
    user.Active = Tools.Tools.IifStr(row.Cells[10].Text);
 
    // Save to current page to Session for retrieving when back from popup edit page... 
    // To store the page index and the primary key User 
    // Id where the edit record was clicked…
    SessionManager.KeyPrimary = Convert.ToInt32(user.UserID).ToString();
    SessionManager.PageIndex = this.GridView1.PageIndex.ToString();
 
    // Call the public function DisplayInf of User's control page. 
    // Pass 'user class' values...
    ucEditUserAcct.DisplayInf(sender, e, user);  
    // Show the user's custom control popup page for editing...
    mpeEditUserAcct.Show();      
}

The above code is an image button click event for editing. They are quite easy, in fact I think the comments code above pretty much explain them in enough detail.

C#
public void CloseModalEditUserAcct()
{
    mpeUserAccountUC.Hide();
    mpeUserAccountUC.Dispose();
    Response.Redirect("DisplayRecord.aspx");
}

The above code call from custom control popup page on closing the user control popup modal..

C#
public void IvokeEdit()
{
   mpeEditUserAcct.Show();
   this.upUserGrid.Update();
}

The above code call from custom control popup page (‘btnUpload_Click(object sender, EventArgs e)’). after executing Upload click button. The custom user’s control makes a post back, therefore closing the popup edit page and goes to grid display. By calling this InvokeEdit display back the popup edit user’s custom control with its update entry…

Points of Interest

The author of this article describes the technical usage on how to Add/Delete/Edit/Update image and, save to SQL database table, and also how to create a menu like an Outlook with faded in slide show.

Added

This is a robust, cross browser fade in slideshow script that incorporates some of your most requested features all rolled into one. Each instance of a fade in slideshow on the page is completely independent of the other, with support for different features selectively enabled for each slideshow.

This unique OutLook looking menu tucks away its contents until user intervention. It supports an unlimited number of categories, and furthermore, works across all DHTML browsers (IE4, NS4+. Mozilla 0.9, Opera5). Works best in a frames page.

History

  • October, 2011: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) ***
Philippines Philippines
MCTS - Microsoft Certified Technology Specialist.
An Accountant.
Had been developed Payroll Accounting System Application
Live in: Quezon City, Metro Manila Philippines
Could reached at email address: ag_mojedo@live.com

Comments and Discussions

 
AnswerHi Dave, Thank you for down loading... Pin
Al Moje1-Nov-11 16:57
Al Moje1-Nov-11 16:57 
QuestionDownload incomplete Pin
Dave Cross1-Nov-11 0:26
professionalDave Cross1-Nov-11 0:26 
AnswerRe: Download incomplete Pin
RedDk1-Nov-11 7:48
RedDk1-Nov-11 7:48 
GeneralRequest to update this article to add link for downloading source code. Pin
Al Moje28-Oct-11 16:38
Al Moje28-Oct-11 16:38 
AnswerThanks for your appreciation. Pin
Al Moje28-Oct-11 16:28
Al Moje28-Oct-11 16:28 
AnswerApology for inconvenience it seems that the source code was not included, but I had compressed it and was included in a zip file. Pin
Al Moje28-Oct-11 15:52
Al Moje28-Oct-11 15:52 
QuestionCan not download source code Pin
Rupesh Kumar Tiwari28-Oct-11 9:36
Rupesh Kumar Tiwari28-Oct-11 9:36 
QuestionPlease Elaborate on efficiency improvement Pin
Rupesh Kumar Tiwari28-Oct-11 9:35
Rupesh Kumar Tiwari28-Oct-11 9:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.