65.9K
CodeProject 正在变化。 阅读更多。
Home

从数据库到 Gridview 显示/存储和检索图像数据,以及鼠标悬停

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.44/5 (21投票s)

2011年10月15日

CPOL

4分钟阅读

viewsIcon

132324

downloadIcon

9943

如何从数据库到 Gridview 显示/存储和检索图像数据,以及鼠标悬停

image002_small.jpg

image003_small.jpg

image004_small.jpg

引言

不久前,我有一个任务是开发一个用户维护模块,该模块应该有一个 Datagrid 视图来显示关于用户的信息,包括相应的图像/图片,并具有相应的命令图像链接选项来编辑/删除,并在详细信息页面上显示完整尺寸的图像,并带有相应的输入信息。此外,在网格的底部中心,应该有一个添加新用户的选项。当单击“添加”按钮时,应该弹出一个自定义控件页面来输入一个条目,并将一些信息和图像存储在一个数据库中,作为项目要求的一部分。这个上传的图像文件应该被调整大小为一个缩略图和一个固定的完整尺寸,然后应该以缩略图自定义控件添加到页面上的图像框中显示。在输入所有前面提到的内容后,应该有一个按钮选项来保存或取消添加选项条目,然后自动返回网格,然后刷新。

本文将演示如何从 SQL 数据库到 gridview 显示/存储和检索图像数据,并且还将演示如何从上传的文件调整大小来创建缩略图/完整尺寸图像,然后将其保存到 SQL 数据库中。我还添加了一个类似放大镜的鼠标悬停图像缩放效果。

数据库

为什么我们应该使用数据库,而不是仅仅在主 ASP.NET 文件夹下有一个虚拟文件夹来存储图像? 好吧,将图像存储在数据库中可能有很多原因,例如:

  • 如果图像二进制数据存储在数据库表中,我们拥有制作任何尺寸图像所需的所有数据,并且它始终看起来像原始图像,此外,我们还可以选择调整图像大小并以指定的Height/width尺寸保存它。
  • 如果图像二进制数据存储在数据库表中,当我们备份数据库时,我们也备份了所有图像。
  • 从 Web 检索图像以进行显示的速度更快。

我并不是说这是唯一的选择。我想这只是一种方法。因此,我认为我应该与您分享我发现的内容。

那么数据库是什么样的呢?

它只包含一个名为 tbl_image 的表,可以使用以下脚本进行设置(包含在本文顶部的对象创建脚本中)。

USE [UserCatalog]
GO

/****** Object:  Table [dbo].[User]    Script Date: 10/12/2011 13:58:22 ******/
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

那么我们如何从这个表中获取数据呢?

让我们看一下这个通用处理程序,它将表中的完整文本信息/图像输出到数据 Gridview,它们非常容易,事实上,我认为下面代码中的注释代码已经足够详细地解释了它们。 所以我不会用更多的解释性文字来让你感到厌烦,因为它很清楚。

这就是它...

//*======================================================================
<%@ WebHandler Language="C#" Class="ShowImage" %>
using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class ShowImage : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        Int32 idNo;

        if (context.Request.QueryString["id"] != null)
            idNo = Convert.ToInt32(context.Request.QueryString["id"]);

        else
            throw new ArgumentException("No parameter specified");

        context.Response.ContentType = "image/jpeg";
        Stream strm = ShowEmpImage(idNo);
        byte[] buffer = new byte[4096];
        int byteSeq = 0;
        try
        {
            byteSeq = strm.Read(buffer, 0, 4096);

        }
        catch (Exception)
        {
            return;
        }

        while (byteSeq >

那么我们如何将数据放入这个表中呢?

让我们看一下自定义控件客户端代码及其后台代码,它们非常容易,事实上,我认为下面代码中的注释代码已经足够详细地解释了它们。 所以我不会用更多的解释性文字来让你感到厌烦,因为它很清楚。

这就是自定义控件…(客户端代码)

//*======================================================================
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserAccountUC.ascx.cs"
    Inherits="UsersControl_UserAccountUC" %>
<%@ Register Assembly="System.Web.Extensions, Version=3.5.0.0, 
	Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="asp" %>

<script type="text/javascript" language="javascript">
   <!--
    function RetrievePicture(imgCtrl, picid) {
        imgCtrl.onload = null;
        imgCtrl.src = 'ShowImage.ashx?id=' + picid;
    }
    -->
</script>

<table width="100%">
    <table frame="box" width="100%">
        <tr>
            <td width="2%">
            </td>
            <td>
                <h1>
                    <asp:Label ID="lblAccountPanel" runat="server" 

			Font-Size="Medium" ForeColor="Black"
                        	Text="User Settings"></asp:Label>
                </h1>
            </td>
            <td align="right">
                <asp:ImageButton ID="btnClose" runat="server" 
			CausesValidation="false" ImageUrl="~/Images/close.gif"
                    OnClick="btnClose_Click" />
            </td>
            <td width="2%">
            </td>
        </tr>
    </table>
    <table frame="box" width="100%">
        <tr>
            <td width="2%">
            </td>
            <td class="style1">
                <asp:FileUpload ID="FileUpload1" runat="server" />
            </td>
            <td width="2%">
            </td>
        </tr>
    </table>
    <table frame="box" width="100%">
        <tr>
            <td width="2%">
            </td>
            <td>
                <div class="pictureWrap" style="float: left; width: 100px; 
				height: 100px; border: 1px solid #ccc;">
                    <asp:UpdatePanel ID="upImg" runat="server" UpdateMode="Conditional">
                        <ContentTemplate>
                            <asp:Image ID="Image1" runat="server" 
				Height="100px" ImageAlign="Middle" Visible="true"
                                Width="100px" OnError="src='images/spicture.jpg'" />
                        </ContentTemplate>
                    </asp:UpdatePanel>
                    <asp:Button ID="btnUpLoad" runat="server" 
				Text="Upload Img." OnClick="btnUpload_Click" />
                </div>
                <br />
                <table>
                    <tr>
                        <td align="right">
                            <label>
                                User Name:
                            </label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtUserName" runat="server" 
				Title="Enter Username" />
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            <label>
                                Password:
                            </label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtPassword" runat="server" 
			    MaxLength="20" TextMode="Password" Title="p@ssw0rd"  />
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            <label>
                                Confirm Password:
                            </label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtPasswordConf" runat="server" 
			   MaxLength="20" TextMode="Password" Title="p@ssw0rd" />
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            <label>
                                First Name:
                            </label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtFirstName" runat="server" />
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            <label>
                                Middle Name:
                            </label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtMiddleName" runat="server" />
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            <label>
                                Last Name:
                            </label>
                        </td>
                        <td>
                            <asp:TextBox ID="txtLastName" runat="server" />
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            <label>
                                Access Level:
                            </label>
                        </td>
                        <td>
                            <asp:DropDownList ID="ddlAccessLevel" 
				runat="server" Width="155">
                                <asp:ListItem Text="Processor" Value="1"> 
				</asp:ListItem>
                                <asp:ListItem Text="Approver" Value="2"> 
				</asp:ListItem>
                            </asp:DropDownList>
                        </td>
                    </tr>
                    <tr>
                        <td align="left">
                             
                        </td>
                        <td>
                            <asp:CheckBox ID="chkActive" runat="server"
                            Text="Is Active" TextAlign="Left" Checked="true" />
                        </td>
                    </tr>
                </table>
            </td>
            <td width="2%">
            </td>
        </tr>
    </table>
    <table frame="box" width="100%">
        <tr>
            <td width="2%">
            </td>
            <td>
                <asp:Label ID="Label1" runat="server"
                ForeColor="Red" Text=""></asp:Label>
            </td>
            <td width="2%">
            </td>
        </tr>
    </table>
    <table frame="box" width="100%">
        <tr align="center">
            <td width="2%">
            </td>
            <td>
                <asp:Button ID="btnSave" runat="server"
                CssClass="button-primary" OnClick="btnSave_Click"
                    TabIndex="100" Text="Save" />
                <asp:Button ID="btnClear" runat="server"
                CssClass="button-primary" OnClick="btnClear_Click"
                    TabIndex="100" Text="Clear" />
            </td>
            <td width="2%">
            </td>
        </tr>
    </table>
</table>
<br />
<asp:HiddenField ID="hidUserID" runat="server" />
<asp:HiddenField ID="hfFileToUpload" runat="server" />
<asp:HiddenField ID="hfUrl" runat="server" />

这就是自定义控件…(后台代码)

//=====================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Configuration;
using System.Data.SqlClient;
using System.Text;
using System.Net;

[Serializable]
internal class Manage
{
    private const string FILEUPLOAD = "FileUpload";
    public static string SessionFileZise
    {
        get
        {
            if (HttpContext.Current.Session[FILEUPLOAD] == null)
            {
                return string.Empty;
            }
            else
            {
                return HttpContext.Current.Session[FILEUPLOAD].ToString();
            }
        }
        set
        {
            HttpContext.Current.Session[FILEUPLOAD] = value;
        }
    }
}

public partial class UsersControl_UserAccountUC : System.Web.UI.UserControl
{
    public void DisplayInfo(object sender, EventArgs e)
    {
        this.Image1 = null;
        Page_Load(sender, e);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.Image1 == null)
        {

        }
    }

    protected void ShowMessage(string message, int fileUploadPos)
    {
        if (fileUploadPos == 0)
        {
            Label1.Text = message;
        }
    }

    protected void btnClose_Click(object sender, ImageClickEventArgs e)
    {

        Page.GetType().InvokeMember("CloseModalUserAccountUC",
        System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
        this.Dispose();
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        this.Image1 = null;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (this.txtPassword.Text != this.txtPasswordConf.Text)
        {
            this.Label1.Text = "Password confirmation not equal!";
            Page.GetType().InvokeMember("IvokeAdd",
            System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
            return;
        }
        if (this.txtFirstName.Text == string.Empty)
        {
            this.Label1.Text = "First Name text box should not empty!";
            Page.GetType().InvokeMember("IvokeAdd",
            System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
            return;
        }
        if (this.txtMiddleName.Text == string.Empty)
        {
            this.Label1.Text = "Middle Name text box should not empty!";
            Page.GetType().InvokeMember("IvokeAdd",
            System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
            return;
        }
        if (this.txtLastName.Text == string.Empty)
        {
            this.Label1.Text = "Last Name text box should not empty!";
            Page.GetType().InvokeMember("IvokeAdd",
            System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
            return;
        }
        if (this.txtPassword.Text.Length < 8)
        {
            this.Label1.Text = "Password length should not lesser that 8!";
            Page.GetType().InvokeMember("IvokeAdd",
            System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
            return;
        }
        bool success = false;
        HttpFileCollection uploadFilCol = null;
        FileUpload img = null;
        FileUpload imgUpload = null;
        var originalSize = Tools.Tools.IifInt(Manage.SessionFileZise);
        try
        {
            HttpFileCollection uploadFil = Request.Files;
            uploadFilCol = uploadFil;
            imgUpload = (FileUpload)Session["UploadFile2"];
            img = (FileUpload)imgUpload;
            originalSize = Tools.Tools.IifInt(Manage.SessionFileZise);
        }
        catch (Exception)
        {
            return;
        }
        var targetDir = Server.MapPath("./upload/");
        var sourceDirFile = Server.MapPath("./images/");
        string[] files = Directory.GetFiles(targetDir);
        if (this.Image1.ImageUrl == string.Empty)
        {
            // Save record with default image NoImage...
            int id = SaveRecord(false, imgUpload, img, originalSize,
                sourceDirFile, files);
        }
        else
        {
            int id = SaveRecord(true, imgUpload, img, originalSize,
               sourceDirFile, files);
        }

        try
        {
            foreach (string file in files)
            {
                File.SetAttributes(file, FileAttributes.Normal);
                File.Delete(file);
            }
        }
        catch (FileNotFoundException)
        {

        }
        this.FileUpload1.Dispose();
        success = true;
        this.Label1.Text = "Record was successfully save.";

        if (success)
        {
            Page.GetType().InvokeMember("CloseModalUserAccountUC", 
		System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
        }
    }

    private int SaveRecord(bool withImage, FileUpload imgUpload, FileUpload img,
        int originalSize, string sourceDirFile, string[] files)
    {
        SqlConnection connection = null;
        User user = new User();
        Byte[] imgByte = null;
        try
        {
            if (img.HasFile && img.PostedFile != null)
            {
                //To create a PostedFile
                HttpPostedFile File = imgUpload.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);
                originalSize = File.ContentLength;
            }
        }
        catch
        {

        }
        try
        {
            user.Username = this.txtUserName.Text;
            user.Password = this.txtPassword.Text;
            user.LastName = this.txtLastName.Text.Substring(0, 1).ToUpper() +
                            this.txtLastName.Text.Substring(1).ToLower();
            user.FirstName = this.txtFirstName.Text.Substring(0, 1).ToUpper() +
                             this.txtFirstName.Text.Substring(1).ToLower();
            user.MiddleName = this.txtMiddleName.Text.ToUpper().Substring(0, 1) +
                              this.txtMiddleName.Text.Substring(1).ToLower();
            user.WorksiteCode = "1";
            user.AccessLevel = Tools.Tools.IifInt
				(this.ddlAccessLevel.SelectedValue.ToString());
            if (this.chkActive.Checked)
            {
                user.Active = "Y";
            }
            else
            {
                user.Active = "N";
            }
            user.DateCreated = DateTime.Now;
            //user.DateUpdated = DateTime.Now;
            user.Worksitedesc = "1";
            //===============================
            string userName = CleanText(user.Username);
            string password = CleanText(user.Password);
            string lastName = CleanText(user.LastName);
            string firstName = CleanText(user.FirstName);
            string middleName = CleanText(user.MiddleName);
            string workSiteCode = CleanText(user.WorksiteCode);
            int accessLevel = user.AccessLevel;
            string active = CleanText(user.Active);
            DateTime dateCreated = user.DateCreated;
            string workSiteDesc = CleanText(user.Worksitedesc);
            // ==========
            Size eimgFullSize = new Size();
            eimgFullSize.Height = 400;
            eimgFullSize.Width = 400;
            //---
            Size eimgThumbSize = new Size();
            eimgThumbSize.Height = 100;
            eimgThumbSize.Width = 100;
            //--
            Size eimgPosterSize = new Size();
            eimgPosterSize.Height = 250;
            eimgPosterSize.Width = 250;
            // Here we have three dimension size of image to produce...
            Byte[] eimgFull = null;
            Byte[] eimgThumb = null;
            Byte[] eimgPoster = null;
            //========
            if (withImage)
            {
                eimgFull = ResizeImageFile(imgByte, eimgFullSize);
                eimgThumb = (Byte[])ResizeImageFile(imgByte, eimgThumbSize);
                eimgPoster = (Byte[])ResizeImageFile(imgByte, eimgPosterSize);
            }
            else
            {
                // Read the default NoImage file
                System.Drawing.Image image1 = System.Drawing.Image.FromFile
					(sourceDirFile + "\\spicture.jpg");
                imgByte = ImageToByte2(image1);
                eimgFull = ResizeImageFile(imgByte, eimgFullSize);
                eimgThumb = (Byte[])ResizeImageFile(imgByte, eimgThumbSize);
                eimgPoster = (Byte[])ResizeImageFile(imgByte, eimgPosterSize);

            }
            // Insert the employee name and image into db
            string conn = ConfigurationManager.ConnectionStrings
				["ConnectionString"].ConnectionString;
            connection = new SqlConnection(conn);
            connection.Open();
            StringBuilder sb = new StringBuilder();
            sb.Append("INSERT INTO dbo.[User](");
            sb.Append("Username,Password,LastName,FirstName,MiddleName,WorksiteCode,");
            sb.Append("AccessLevel,Active,DateCreated,Worksitedesc,Picture,ImageFull ");
            sb.Append(") VALUES (");
            sb.Append("@userName ,@password,@lastName,@firstName,");
            sb.Append("@middleName,@worksiteCode,@accessLevel,@active,");
            sb.Append("@dateCreated,@worksitedesc,");
            sb.Append("@eimgThumb,@eimgFull) ");  // For Picture image
            sb.Append(" SELECT @@IDENTITY");
            string sql = sb.ToString();
            //----------
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@userName", user.Username);
            cmd.Parameters.AddWithValue("@password", user.Password);
            cmd.Parameters.AddWithValue("@lastName", user.LastName);
            cmd.Parameters.AddWithValue("@firstName", user.FirstName);
            cmd.Parameters.AddWithValue("@middleName", user.MiddleName);
            cmd.Parameters.AddWithValue("@worksiteCode", user.WorksiteCode);
            cmd.Parameters.AddWithValue("@accessLevel", user.AccessLevel);
            cmd.Parameters.AddWithValue("@active", user.Active);
            cmd.Parameters.AddWithValue("@dateCreated", user.DateCreated);
            cmd.Parameters.AddWithValue("@worksitedesc", user.Worksitedesc);
            cmd.Parameters.AddWithValue("@eimgThumb", eimgThumb);
            cmd.Parameters.AddWithValue("@eimgFull", eimgFull);
            int id = Convert.ToInt32(cmd.ExecuteScalar());
            connection.Close();

            Size targetSize = new Size();
            targetSize.Width = 100;
            targetSize.Height = 100;

            //=========
            // Save File to Show sub directory
            // Must be in fix length
            string targetPath = Server.MapPath("./Show/");
            string fleName = (firstName.Trim() + "_" + 
		middleName.Substring(0, 1) + "_" + lastName).Trim() + ".jpg";
            File.WriteAllBytes(@targetPath + @fleName, eimgPoster);
            return id;
        }
        catch
        {
            return 0;
        }
    }
    private string CleanText(string p)
    {
        string str = string.Empty;
        if (p != string.Empty)
        {
            str = p.Replace(" ", "");
        }
        return str;
    }

    public static byte[] ImageToByte2(System.Drawing.Image img)
    {
        byte[] byteArray = new byte[0];
        using (MemoryStream stream = new MemoryStream())
        {
            img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
            stream.Close();
            byteArray = stream.ToArray();
        }
        return byteArray;
    }

    private byte[] ResizeImageFile(byte[] imageFile, Size targetSize)
    {
        using (System.Drawing.Image oldImage = 
		System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
        {
            Size newSize = CalculateDimensions
		(oldImage.Size, targetSize.Height, targetSize.Width);
            using (Bitmap newImage = new Bitmap
		(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
            {
                using (Graphics canvas = Graphics.FromImage(newImage))
                {
                    canvas.SmoothingMode = SmoothingMode.AntiAlias;
                    canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
                    MemoryStream m = new MemoryStream();
                    newImage.Save(m, ImageFormat.Jpeg);
                    return m.GetBuffer();
                }
            }
        }
    }

    private Size CalculateDimensions(Size oldSize, int targetH, int targetW)
    {
        Size newSize = new Size();
        if (oldSize.Height > oldSize.Width)
        {
            newSize.Width = targetW;
            newSize.Height = targetH;
        }
        else
        {
            //Make the image as uniform with fix size.
            newSize.Width = targetW;
            newSize.Height = targetH;
        }
        return newSize;
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        this.btnSave.Enabled = false;
        bool hasFile = false;
        string fileName = string.Empty;
        HttpPostedFile file = null;
        HttpFileCollection uploadFilCol = Request.Files;

        hasFile = true;
        HttpPostedFile file2 = uploadFilCol[0];
        if (file2.ContentLength == 0)
        {
            return;
        }
        file = uploadFilCol[0];
        Session["UploadFile2"] = FileUpload1;
        Manage.SessionFileZise = file.ContentLength.ToString();
        string fileExt = Path.GetExtension(file.FileName).ToLower();
        fileName = Path.GetFileName(file.FileName);
        if (fileName != string.Empty)
        {
            try
            {
                if (fileExt == ".jpg" || fileExt == ".gif")
                {
                    file.SaveAs(Server.MapPath("./upload/") + fileName);
                    this.ShowMessage(" " + fileName + " Successfully Uploaded", 0);

                }
                else
                {
                    // We do allow image file only
                    this.Label1.Text = "Valid files to upload is .jpg and .gif only!";
                    Page.GetType().InvokeMember("IvokeAdd", 
			System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
                    return;
                }
                this.hfUrl.Value = fileName;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        string fileImgName = "~/upload/" + fileName;
        this.Image1.ImageUrl = fileImgName;
        upImg.Update();

        if (hasFile)
        {
            this.btnSave.Enabled = true;
            Page.GetType().InvokeMember("IvokeAdd", 
		System.Reflection.BindingFlags.InvokeMethod, null, Page, null);
        }
        else
        {
            this.btnSave.Enabled = false;
        }
    }
}

那么我们如何使 DataGridView 在每个事件参数 Add/Detail View 上工作呢?

首先,我们看一下它的客户端代码

这就是它...

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

<%@ Register Assembly="AjaxControlToolkit" 
	Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<%@ Register Src="~/UsersControl/Loader.ascx" TagName="Loader" TagPrefix="uc2" %>
<%@ Register Src="~/UsersControl/UserAccountUC.ascx" 
	TagName="UserAccountUC" TagPrefix="uc3" %>
<!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>
    <link rel="Stylesheet" type="text/css" href="css/XPStyle.css" />
    <style type="text/css">
        .AlgemBackground
        {
            background-color: #000000;
            opacity: 0.75;
            filter: alpha(opacity=70);
        }
    </style>
</head>

<script type="text/javascript">

    function ShowModal() {
        var modalPopupBehavior = $find('loader');

        modalPopupBehavior.updated();
        return true;
    }

</script>

<body class="bg">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <cc1:ModalPopupExtender runat="server" ID="mpeLoader" 
		BehaviorID="loader" TargetControlID="hfloader"
            PopupControlID="panelLoading" BackgroundCssClass="modalBackground" 
			DropShadow="False">
        </cc1:ModalPopupExtender>
        <asp:Panel runat="server" ID="panelLoading">
            <uc2:Loader ID="ucLoader" runat="server" />
        </asp:Panel>
        <asp:Button runat="server" ID="hfloader" Style="display: none" />
        <table width="100%">
            <tr align="center">
                <td>
                    <h2>
                        User's Maintenance
                    </h2>
                </td>
            </tr>
            <tr align="center">
                <td>
                    <asp:UpdatePanel ID="upUserGrid" runat="server" 
			UpdateMode="Conditional">
                        <ContentTemplate>
                            <asp:GridView ID="GridView1" runat="server"
                            AutoGenerateColumns="False" AllowPaging="True"
                                OnPageIndexChanging="GridView1_PageIndexChanging"
                                PageSize="3" OnRowCommand="GridView1_RowCommand"
                                EmptyDataText="*** No Record ***">
                                <EmptyDataRowStyle ForeColor="#CC3300" />
                                <Columns>
                                    <asp:TemplateField ItemStyle-HorizontalAlign="Center" 
				HeaderText="Delete">
                                        <ItemTemplate>
                                            <asp:ImageButton ID="gImgBtnDelete"
                                            runat="server" ToolTip="Delete" 
					OnClick="gImgBtnDelete_Click"
                                                OnClientClick="return confirm
                                                ('Are you sure you want to delete 
						this records?');"
                                                ImageUrl="~/Images/btn_delete.gif" />
                                        </ItemTemplate>
                                        <ItemStyle HorizontalAlign="Center" />
                                    </asp:TemplateField>
                                    <asp:BoundField DataField="UserID"
                                    HeaderText="User ID" InsertVisible="False" 
					ReadOnly="True" />
                                    <asp:BoundField DataField="Username" 
					HeaderText="User Name" />
                                    <asp:BoundField DataField="Password"
                                    HeaderText="Password" ItemStyle-ForeColor="Blue">
                                        <ItemStyle ForeColor="Blue" />
                                    </asp:BoundField>
                                    <asp:BoundField DataField="LastName" 
					HeaderText="LastName" />
                                    <asp:BoundField DataField="FirstName" 
					HeaderText="FirstName" />
                                    <asp:BoundField DataField="MiddleName" 
					HeaderText="MiddleName" />
                                    <asp:BoundField DataField="WorksiteCode"
                                    HeaderText="WorksiteCode" Visible="false" />
                                    <asp:BoundField DataField="AccessLevel" 
					HeaderText="AccessLevel" />
                                    <asp:BoundField DataField="Active" 
					HeaderText="Active" />
                                    <asp:BoundField DataField="DateCreated" 
					HeaderText="DateCreated" />
                                    <asp:BoundField DataField="DateUpdated" 
					HeaderText="DateUpdated" />
                                    <asp:BoundField DataField="Worksitedesc" 
					HeaderText="Worksitedesc" Visible="false" />
                                    <asp:BoundField DataField="Username" 
					HeaderText="User Name" />
                                    <asp:TemplateField HeaderText="Image"
                                    ItemStyle-HorizontalAlign="Justify" 
					ItemStyle-VerticalAlign="Middle">
                                        <ItemTemplate>
                                            <a href='PhotoDetail.aspx?id=
					<%# Eval("UserID") %>'>
                                                <img src='<%# "ShowImage.ashx?Id=" +
                                                Eval("UserID") %>' style="border: 
							4px solid white"
                                                    class="" alt='Deleted 
						Photo Album Number
                                                    <%# Eval("Picture") %>' /></a>
                                        </ItemTemplate>
                                        <ItemStyle HorizontalAlign="Justify" 
					VerticalAlign="Middle"></ItemStyle>
                                    </asp:TemplateField>
                                </Columns>
                            </asp:GridView>
                        </ContentTemplate>
                    </asp:UpdatePanel>
                </td>
            </tr>
        </table>
        <table width="100%">
            <tr align="center">
                <td>
                    <asp:Button ID="btnAddNew" runat="server" Text="Add New" 
			OnClick="btnAddNew_Click"
                        OnClientClick="return ShowModal();" />
                    <asp:Button ID="btnBack" runat="server" Text="Back" 
			OnClick="btnBack_Click" />
                </td>
            </tr>
        </table>
        <cc1:ModalPopupExtender runat="server" ID="mpeUserAccountUC" 
			TargetControlID="hfPopAddNew"
            PopupControlID="pnlUserAccountUC" BackgroundCssClass="AlgemBackground" 
			BehaviorID="mpeBehavior3"
            DropShadow="false" PopupDragHandleControlID="pnlUserAccountUC">
        </cc1:ModalPopupExtender>
        <asp:Panel runat="server" ID="pnlUserAccountUC" Style="display: none; 
			background-color: White;"
            Width="70%">
            <uc3:UserAccountUC runat="server" ID="ucUserAccountUC" />
        </asp:Panel>
        <asp:Button runat="server" ID="hfPopAddNew" Style="display: none" />
    </div>
    <table>
        <tr>
            <td>
                <asp:HiddenField ID="hfKeyId" runat="server" />
                <asp:HiddenField ID="hfPageIndex" runat="server" />
                <asp:HiddenField ID="hfAddNew" runat="server" />
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

这就是 DataGridView 的后台代码,它们非常容易,事实上,我认为下面代码中的注释代码已经足够详细地解释了它们。 所以我不会用更多的解释性文字来让你感到厌烦,因为它很清楚。

这就是它...

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Text;
using System.Data;
using Utils;

public partial class DisplayRecord : System.Web.UI.Page
{
    string sqlConnection = ConfigurationManager.ConnectionStrings
				["ConnectionString"].ConnectionString;
    SqlConnection conn;
    SqlCommand cmd;
    List<User> lstUser = new List<User>();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (SessionManager.PageIndex != string.Empty)
            {
                this.hfKeyId.Value = SessionManager.KeyPrimary;
                this.GridView1.PageIndex = Convert.ToInt32(SessionManager.PageIndex);
            }
            BindGrid();
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("DisplayRecord.aspx");
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindGrid();
    }

    protected void BindGrid()
    {

        List<User> lst = new List<User>();
        try
        {
            using (conn = new SqlConnection(sqlConnection))
            {
                conn.Open();

                StringBuilder sbQry = new StringBuilder();
                sbQry.Append("select ");
                sbQry.Append("UserID,Username,Password,LastName,FirstName,MiddleName,");
                sbQry.Append("WorksiteCode,AccessLevel,Active,
				DateCreated,DateUpdated,Worksitedesc, ");
                sbQry.Append("Picture,ImageFull FROM dbo.[User]");
                using (cmd = new SqlCommand(sbQry.ToString(), conn))
                {
                    cmd.CommandType = CommandType.Text;

                    using (SqlDataReader dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            User temp = new User();
                            temp.UserID = Tools.Tools.IifInt(dr["UserID"]);
                            temp.Username = Tools.Tools.IifStr(dr["Username"]);
                            temp.Password = Tools.Tools.IifStr(dr["Password"]);
                            temp.LastName = Tools.Tools.IifStr(dr["LastName"]);
                            temp.FirstName = Tools.Tools.IifStr(dr["FirstName"]);
                            temp.MiddleName = Tools.Tools.IifStr(dr["MiddleName"]);
                            temp.WorksiteCode = Tools.Tools.IifStr(dr["WorksiteCode"]);
                            temp.AccessLevel = Tools.Tools.IifInt(dr["AccessLevel"]);
                            temp.Active = Tools.Tools.IifStr(dr["Active"]);
                            temp.DateCreated = Tools.Tools.IifDT(dr["DateCreated"]);
                            temp.DateUpdated = Tools.Tools.IifDT(dr["DateUpdated"]);
                            temp.WorksiteCode = Tools.Tools.IifStr(dr["Worksitedesc"]);
                            temp.Picture = dr["Picture"];
                            temp.ImageFull = dr["ImageFull"];
                            lst.Add(temp);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        Session["ListUser"] = lst;
        this.GridView1.DataSource = lst;
        this.GridView1.DataBind();
    }

    protected void gImgBtnDelete_Click(object sender, EventArgs e)
    {
        ImageButton iBtnDelete = sender as ImageButton;
        GridViewRow row = (GridViewRow)iBtnDelete.NamingContainer;
        int idNo = Convert.ToInt32(row.Cells[1].Text);
        bool success = DeleteEntry(idNo);
        if (success)
        {
            SessionManager.KeyPrimary = this.hfKeyId.Value;
            SessionManager.PageIndex = this.hfPageIndex.Value;
            Response.Redirect("DisplayRecord.aspx");
        }
    }

    private bool DeleteEntry(int id)
    {
        bool result = false;

        conn = new SqlConnection(sqlConnection);
        conn.Open();
        SqlTransaction trans = conn.BeginTransaction();
        using (conn)
        {
            try
            {

                string script = string.Empty;

                script = "DELETE FROM dbo.[User] WHERE UserId = " + id.ToString();
                using (cmd = new SqlCommand(script, conn))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Transaction = trans;
                    cmd.ExecuteNonQuery();
                }

                trans.Commit();
                result = true;
            }
            catch (Exception)
            {
                trans.Rollback();
                result = false;
            }
        }
        this.upUserGrid.Update();
        return result;
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {

    }
    protected void btnAddNew_Click(object sender, EventArgs e)
    {
        ucUserAccountUC.DisplayInfo(sender, e);
        mpeUserAccountUC.Show();
    }

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

    public void IvokeAdd()
    {
        mpeUserAccountUC.Show();
        this.upUserGrid.Update();
    }
    public void CloseModalEditUserAcct()
    {
        mpeUserAccountUC.Hide();
        mpeUserAccountUC.Dispose();
        Response.Redirect("DisplayRecord.aspx");
    }
}

关注点

本文的作者描述了如何将图像数据展示/存储和检索到 SQL 数据库的 gridview 中的技术用法,并演示了如何将上传文件中的图像调整大小并保存到表中。

精选图像缩放器 @ http://www.dynamicdrive.com/dynamicindex4/

此脚本可让您在鼠标悬停在任何图像上时查看该图像的放大部分。 放大镜会出现在图像旁边,根据需要显示放大的区域。 用户可以使用鼠标滚轮切换缩放级别。 它非常适合用于产品图像、照片或其他具有大量细节的图像。

历史

  • 2011 年 10 月 12 日:初始版本
© . All rights reserved.