在 Gridview 中显示 varbinary 图像

2024-03-08

更新 - 表定义 - ICTSQL 中的表名称剩余 - Windows 身份验证 剩余ID int 部门nchar(50) 类别 nchar(25) 项目 nchar(75) 可见位 TransferableImage varbinary(MAX)

我有一个 SQL Server 表,其中包含varbinary(MAX)称为的列TransferableImage在表中Surplus- 服务器名称 ICTSQL。

使用 Visual Basic,我想在网页网格视图中显示此图像。我找到了执行此操作的代码,我知道图像存在于我拥有的一条记录中,但图像没有出现,而且我尝试了太多的方法,所以我将其带给专家。网格中的其他项目填充,只是不显示图像。没有错误。

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
        AutoGenerateColumns="False" DataSourceID="SqlDataSource1" 
        AllowSorting="True">
    <Columns>
        <asp:TemplateField HeaderText="Image">
            <ItemTemplate>
                <asp:Image ID="TransferableImage" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        ...
    </Columns>
</asp:GridView>

其背后的VB代码:

Public Class About

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using conn As SqlConnection = New SqlConnection(constr)
            Using sda As SqlDataAdapter = New SqlDataAdapter("SELECT * FROM surplus", conn)
                Dim dt As DataTable = New DataTable()
                sda.Fill(dt)
                GridView1.DataSource = dt
                GridView1.DataBind()
            End Using
        End Using
    End If
End Sub

Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim dr As DataRowView = CType(e.Row.DataItem, DataRowView)
        Dim imageUrl As String = "data:image/jpg;base64," & Convert.ToBase64String(CType(dr("Data"), Byte()))
        CType(e.Row.FindControl("Image1"), Image).ImageUrl = imageUrl
    End If
End Sub

End Class

仅供参考——我已经很久没有编程了,所以这就像重新学习一切。当然,老板昨天需要它。提前致谢!


下面将展示如何从 SQL Server 检索图像并将其显示在GridView在 ASP.NET 网页上。

在数据库中创建一个表:

CREATE TABLE Surplus([Surplus Id] int not null, 
Department nchar(50),
Category nchar(25),
Item nchar(75),
Visible bit,
TransferableImage varbinary(max),
CONSTRAINT PK_Surplus_SurplusId PRIMARY KEY([Surplus Id]));

Note:如果表列名包含空格,则需要将其括起来[]。我更喜欢创建不带空格的数据库列名称。


开始之前,请确保安装了适当的 Visual Studio 工作负载/单独组件。

VS 2017:

  • Open 视觉工作室安装程序
  • Click Modify
  • Click 工作负载 tab
  • 确保检查以下内容:.NET 桌面开发、ASP.NET 和 Web 开发、数据存储和处理
  • Click 单独的组件
  • 在 .NET 下,检查:.NET框架4.7.2 SDK and .NET Framework 4.7.2 目标包
  • 在“代码工具”下,检查ClickOnce发布 and NuGet 包管理器
  • Select 全部下载,然后安装
  • Click Modify

VS 2017:

创建一个新项目

  • 打开视觉工作室
  • Click File
  • Select New
  • Select Project
  • 在左侧,单击视觉基础
  • 在左侧,单击Web
  • Select ASP.NET Web 应用程序(.NET 框架);对于“框架”,选择.NET框架4.7.2
  • Click OK
  • Select Empty
  • Click OK

Note: 确保选项严格 https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/option-strict-statement已打开。

查找您的 Windows 服务器名称:

  • 打开cmd窗口
  • Type: hostname

查找您的 SQL Server 实例名称:

  • 打开cmd窗口
  • type: sc query | find /i "SQL Server"

Note: 你会看到类似下面的内容:DISPLAY_NAME: SQL Server (SQLEXPRESS)。 SQL Server 实例名称位于()。在本例中,SQL Server 实例名称为:SQLEXPRESS

我们将使用以下内容:

  • Windows 服务器名称: ICTSQL
  • SQL Server 实例名称: ICTSQL
  • 数据库名称: ICTSQL
  • 认证类型:Windows 身份验证

Note:我不建议将 Windows 服务器、数据库实例和数据库名称命名为相同的名称,因为这可能会导致混乱。然而,我的理解是,截至发帖时,他们目前都有这个名字ICTSQL.

打开解决方案资源管理器

  • 在 VS 菜单中,单击View
  • Select 解决方案浏览器

将连接字符串添加到 Web.config

  • 在解决方案资源管理器中,双击网页配置

在下面的代码中,修改里面的代码<connectionStrings>...</connectionStrings>为了您的环境。看SQL Server 连接字符串 https://www.connectionstrings.com/microsoft-data-sqlclient/了解更多信息。

网页配置

<?xml version="1.0" encoding="utf-8"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="ictsqlConnection" connectionString="Data Source=.\SQLEXPRESS;Database=ICTSQL;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.7.2"/>
    <httpRuntime targetFramework="4.7.2"/>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
</configuration>

在下面的代码中,我改编了菜单的代码这个帖子 https://social.msdn.microsoft.com/Forums/en-US/1819233e-113b-4c35-b474-c831eb332cf1/creating-menu-bar-in-aspnet?forum=aspwebforms

打开属性窗口

  • 在 VS 菜单中,单击View
  • Select 属性窗口

将 XML 文件添加到项目中(名称:剩余菜单.xml)

  • 在 VS 菜单中,单击Project
  • Select 添加新项目...
  • 在左侧,单击Data
  • Click XML File(名称:剩余菜单.xml)
  • 在属性窗口中,设置复制到输出目录 to 始终复制

剩余菜单.xml:

<?xml version="1.0" encoding="utf-8" ?>
<surplusMenu text="Home" url="./default.aspx">
    <main text="Surplus" url="./addDatabaseRecord.aspx">
        <page text="Add Record" url ="./addDatabaseRecord.aspx" />
    </main>
</surplusMenu>

添加模块(名称:Module1.vb)

  • 在解决方案资源管理器中,右键单击 (例如:DatabaseGridViewTest)
  • Select Add
  • Select 新物品...
  • 在左侧,单击Code
  • Select Module(名称:Module1.vb)
  • Click Add

模块1.vb

Imports System.Drawing
Imports System.IO

Module Module1
    Public Function ResizeImage(imageBytes As Byte(), maxWidth As Integer, maxHeight As Integer) As Byte()
        Dim modifiedImageBytes As Byte()
        Dim ratioX As Double = 0
        Dim ratioY As Double = 0
        Dim ratio As Double = 0
        Dim newWidth As Integer = 0
        Dim newHeight As Integer = 0

        Using ms As MemoryStream = New MemoryStream(imageBytes)
            Using originalImg As Bitmap = New Bitmap(ms)
                ratioX = CType(maxWidth, Double) / originalImg.Width
                ratioY = CType(maxHeight, Double) / originalImg.Height

                'set value
                ratio = Math.Min(ratioX, ratioY)

                'calculate new width and height
                newWidth = CType((CType(originalImg.Width, Double) * ratio), Integer)
                newHeight = CType((CType(originalImg.Height, Double) * ratio), Integer)

                'create new Bitmap with desired size
                Using newImg As Bitmap = New Bitmap(newWidth, newHeight)
                    Using g As Graphics = Graphics.FromImage(newImg)
                        g.DrawImage(originalImg, 0, 0, newWidth, newHeight)
                        g.Save()
                    End Using

                    Using newImgMs As MemoryStream = New MemoryStream()
                        'save in jpeg format
                        newImg.Save(newImgMs, Imaging.ImageFormat.Jpeg)

                        'save as Byte()
                        modifiedImageBytes = newImgMs.ToArray()
                    End Using
                End Using
            End Using
        End Using

        Return modifiedImageBytes
    End Function
End Module

添加网页表单(名称:addDatabaseRecord.aspx)

  • 在解决方案资源管理器中,右键单击 (例如:DatabaseGridViewTest)
  • Select Add
  • Select 新物品...
  • Select Web Form(名称:addDatabaseRecord.aspx)
  • Click Add

添加数据库记录.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="addDatabaseRecord.aspx.vb" Inherits="DatabaseGridViewTest.addDatabaseRecord" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>

    <body>
        <form id="form1" runat="server">
            <!-- menu -->
            <div id="menu" style="background-color:cornflowerblue"  >
                <asp:XmlDataSource runat="server" ID="xmldatasource" DataFile="surplusMenu.xml"></asp:XmlDataSource>

                <asp:Menu ID="menuNavigator" runat="server" Width="760px" DisappearAfter="0" StaticSubMenuIndent="10px" StaticEnableDefaultPopOutImage="False" Orientation="Horizontal" StaticDisplayLevels="2" DataSourceID="xmldatasource" ItemWrap="True" >
                    <StaticHoverStyle Height="34px" Width="50px" BackColor="#93C6FF" />
                    <StaticMenuItemStyle HorizontalPadding="8px" Width="50px" Height="34px" CssClass="menustyle" ForeColor="Black" VerticalPadding="2px" />
                    <DynamicMenuStyle Width="50px" />
                    <DynamicSelectedStyle BackColor="#507CD1"></DynamicSelectedStyle>
                    <DynamicHoverStyle BackColor="#6597F0" ForeColor="White" Font-Bold="True" />
                    <DynamicMenuItemStyle BackColor="#0A398D" Width="125px" HorizontalPadding="15px" VerticalPadding="6px" ForeColor="White" Font-Size="14px" />
                    <DataBindings>
                        <asp:MenuItemBinding DataMember="surplusMenu" TextField="text" NavigateUrlField="url"></asp:MenuItemBinding>
                        <asp:MenuItemBinding DataMember="main" NavigateUrlField="url" TextField="text"></asp:MenuItemBinding>
                        <asp:MenuItemBinding DataMember="page" NavigateUrlField="url" TextField="text"></asp:MenuItemBinding>
                    </DataBindings>
                </asp:Menu>  
            </div> 

            <div style="position:absolute;left:300px">
                <h2>Surplus Record Entry</h2>
            </div>

            <div>
                <!-- Surplus Id -->
                <asp:Label ID="LabelSurplusId" runat="server" Text="Surplus Id:" style="position:absolute;left:50px;top:100px;font-weight:bold"></asp:Label>
                <asp:TextBox ID="TextBoxSurplusId" runat="server" style="position:absolute;left:200px;top:100px;width:75px" ></asp:TextBox>

                <!-- Department, Category -->
                <asp:Label ID="LabelDepartment" runat="server" Text="Department:" style="position:absolute;left:50px;top:140px;font-weight:bold"></asp:Label>
                <asp:TextBox ID="TextBoxDepartment" runat="server" style="position:absolute;left:200px;top:140px;width:150px"></asp:TextBox>

                <asp:Label ID="LabelCategory" runat="server" Text="Category:" style="position:absolute;left:450px;top:140px;font-weight:bold"></asp:Label>
                <asp:TextBox ID="TextBoxCategory" runat="server" style="position:absolute;left:550px;top:140px;width:150px"></asp:TextBox>

                <!-- Item, IsVisible -->
                <asp:Label ID="LabelItem" runat="server" Text="Item:" style="position:absolute;left:50px;top:180px;font-weight:bold"></asp:Label>
                <asp:TextBox ID="TextBoxItem" runat="server" style="position:absolute;left:200px;top:180px;width:150px"></asp:TextBox>

                <asp:CheckBox ID="CheckBoxIsVisible" runat="server" style="position:absolute;left:448px;top:180px;width:125px;font-weight:bold" Text="  Is Visible?" Checked="true"/>

                <!-- Transferable Image -->
                <asp:Label ID="LabelTransferableImage" runat="server" Text="Transferable Image:" style="position:absolute;left:50px;top:220px;font-weight:bold"></asp:Label>
                <asp:FileUpload ID="FileUploadTransferableImage" runat="server" style="position:absolute;left:200px;top:220px;font-weight:bold"/>
            </div>

            <div>
                <asp:Button ID="ButtonSave" runat="server" Text="Save" style="position:absolute;left:350px;top:280px;height:40px;width:125px" OnClick="ButtonSave_Click" />
            </div>
        
            <div>
                <asp:Label ID="LabelMsg" runat="server" Text="" style="position:absolute;left:350px;top:340px"></asp:Label>
            </div>
        </form>
    </body>
</html>

在解决方案资源管理器中,右键单击添加数据库记录.aspx。选择查看代码

添加数据库记录.aspx.vb

Note:如果(数据库)表列名包含空格,则需要将其括起来[].

Imports System.Configuration
Imports System.Data.SqlClient

Public Class addDatabaseRecord
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        SetSurplusId()
    End Sub

    Protected Sub ClearPage()
        TextBoxSurplusId.Text = String.Empty
        TextBoxDepartment.Text = String.Empty
        TextBoxCategory.Text = String.Empty
        TextBoxItem.Text = String.Empty
        CheckBoxIsVisible.Checked = True

        'dispose
        FileUploadTransferableImage.Dispose()

        'create new instance
        FileUploadTransferableImage = New FileUpload()
    End Sub

    Private Function GetNextSurplusId() As Integer
        Dim nextSurplusId As Integer = 0
        Dim connectionStr As String = ConfigurationManager.ConnectionStrings("ictsqlConnection").ConnectionString
        Dim sqlText As String = "SELECT Max([Surplus Id]) from Surplus;"

        Using con As SqlConnection = New SqlConnection(connectionStr)
            'open
            con.Open()

            Using cmd As SqlCommand = New SqlCommand(sqlText, con)
                'get last surplus id from database and increment it by 1
                nextSurplusId = (DirectCast(cmd.ExecuteScalar(), Integer)) + 1
            End Using
        End Using

        Return nextSurplusId
    End Function

    Protected Function SaveSurplusRecord(surplusId As Integer, department As String, category As String, item As String, visible As Boolean, transferableImageBytes As Byte()) As Integer
        Dim rowsAffected As Integer = 0
        Dim connectionStr As String = ConfigurationManager.ConnectionStrings("ictsqlConnection").ConnectionString
        Dim sqlText As String = "INSERT INTO Surplus([Surplus Id], Department, Category, Item, Visible, TransferableImage) VALUES(@surplusId, @department, @category, @item, @visible, @transferableImage);"

        Using con As SqlConnection = New SqlConnection(connectionStr)
            'open
            con.Open()

            Using cmd As SqlCommand = New SqlCommand(sqlText, con)

                cmd.Parameters.Add("@surplusId", SqlDbType.Int).Value = surplusId

                If String.IsNullOrEmpty(department) Then
                    cmd.Parameters.Add("@department", SqlDbType.NChar).Value = DBNull.Value
                Else
                    cmd.Parameters.Add("@department", SqlDbType.NChar).Value = department
                End If

                If String.IsNullOrEmpty(category) Then
                    cmd.Parameters.Add("@category", SqlDbType.NChar).Value = DBNull.Value
                Else
                    cmd.Parameters.Add("@category", SqlDbType.NChar).Value = category
                End If

                If String.IsNullOrEmpty(item) Then
                    cmd.Parameters.Add("@item", SqlDbType.NChar).Value = DBNull.Value
                Else
                    cmd.Parameters.Add("@item", SqlDbType.NChar).Value = item
                End If

                'size = -1 is needed to exceed 8000 bytes; it maps to varbinary(max)
                cmd.Parameters.Add("@transferableImage", SqlDbType.VarBinary, -1).Value = transferableImageBytes

                'execute
                rowsAffected = cmd.ExecuteNonQuery()
            End Using
        End Using

        Return rowsAffected
    End Function

    Private Sub SetSurplusId()
        Dim nextSurplusId As Integer = GetNextSurplusId()

        If nextSurplusId > 0 Then
            TextBoxSurplusId.Text = nextSurplusId.ToString()
        End If
    End Sub

    Protected Sub ButtonSave_Click(sender As Object, e As EventArgs)
        If FileUploadTransferableImage.HasFile() Then
            LabelMsg.Text = "Filename: " & FileUploadTransferableImage.FileName & " File bytes: " & FileUploadTransferableImage.FileBytes.Length

            Dim surplusIdInt As Integer = 0

            If Int32.TryParse(TextBoxSurplusId.Text, surplusIdInt) Then
                'save record to database
                Dim rowsAffected As Integer = SaveSurplusRecord(surplusIdInt, TextBoxDepartment.Text, TextBoxCategory.Text, TextBoxItem.Text, CheckBoxIsVisible.Checced, FileUploadTransferableImage.FileBytes())

                If rowsAffected > 0 Then
                    LabelMsg.Text = String.Format("Record saved (Surplus Id: {0}; Item: {1})", surplusIdInt.ToString(), TextBoxItem.Text)

                    ClearPage()
                    SetSurplusId()

                    'System.Threading.Thread.Sleep(1000)
                    'Response.Redirect("addDatabaseRecord.aspx")
                Else
                    LabelMsg.Text = String.Format("Error: Record not saved (Surplus Id: {0}; Item: {1})", surplusIdInt.ToString(), TextBoxItem.Text)
                End If
            Else
                LabelMsg.Text = String.Format("Error: Surplus Id must be an integer. (Surplus Id: '{0}')", TextBoxSurplusId.Text)
            End If
        Else
            LabelMsg.Text = "Error: Transferable image has not been selected."
        End If
    End Sub
End Class

添加网页表单(名称:默认.aspx)

  • 在解决方案资源管理器中,右键单击 (例如:DatabaseGridViewTest)
  • Select Add
  • Select 新物品...
  • Select Web Form(名称:默认.aspx)
  • Click Add

默认.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="default.aspx.vb" Inherits="DatabaseGridViewTest._default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <!-- menu -->
            <div id="menu" style="background-color:cornflowerblue"  >
                <asp:XmlDataSource runat="server" ID="xmldatasource" DataFile="surplusMenu.xml"></asp:XmlDataSource>

                <asp:Menu ID="menuNavigator" runat="server" Width="760px" DisappearAfter="0" StaticSubMenuIndent="10px" StaticEnableDefaultPopOutImage="False" Orientation="Horizontal" StaticDisplayLevels="2" DataSourceID="xmldatasource" ItemWrap="True" >
                    <StaticHoverStyle Height="34px" Width="50px" BackColor="#93C6FF" />
                    <StaticMenuItemStyle HorizontalPadding="8px" Width="50px" Height="34px" CssClass="menustyle" ForeColor="Black" VerticalPadding="2px" />
                    <DynamicMenuStyle Width="50px" />
                    <DynamicSelectedStyle BackColor="#507CD1"></DynamicSelectedStyle>
                    <DynamicHoverStyle BackColor="#6597F0" ForeColor="White" Font-Bold="True" />
                    <DynamicMenuItemStyle BackColor="#0A398D" Width="125px" HorizontalPadding="15px" VerticalPadding="6px" ForeColor="White" Font-Size="14px" />
                    <DataBindings>
                        <asp:MenuItemBinding DataMember="surplusMenu" TextField="text" NavigateUrlField="url"></asp:MenuItemBinding>
                        <asp:MenuItemBinding DataMember="main" NavigateUrlField="url" TextField="text"></asp:MenuItemBinding>
                        <asp:MenuItemBinding DataMember="page" NavigateUrlField="url" TextField="text"></asp:MenuItemBinding>
                    </DataBindings>
                </asp:Menu>  
            </div>    

            <div>
                <asp:Label ID="LabelMsg" runat="server" Text="" style="position:absolute;left:50px; top:60px"></asp:Label>
            </div>

            <div style="position:absolute;left:50px; top:100px">
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"  DataKeyNames="Surplus Id" GridLines="Both">
                    <Columns>
                        <asp:BoundField DataField="Surplus Id" HeaderText="Surplus Id" ItemStyle-HorizontalAlign="Center" Visible="True" />
                        <asp:BoundField DataField="Department" HeaderText="Department" ItemStyle-HorizontalAlign="Center" />
                        <asp:BoundField DataField="Category" HeaderText="Category" ItemStyle-HorizontalAlign="Center" />
                        <asp:BoundField DataField="Item" HeaderText="Item" ItemStyle-HorizontalAlign="Left" />
                        <asp:BoundField DataField="Visible" HeaderText="Visible" ItemStyle-HorizontalAlign="Center" />

                        <asp:TemplateField HeaderText="Transferable Image" ItemStyle-HorizontalAlign="Center">
                            <ItemTemplate>
                                <asp:Image ID="TransferableImg" runat="server" ImageUrl='<%# Eval("TransferableImageBase64", "{0}") %>' />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </div>
        </form>
    </body>
</html>

在解决方案资源管理器中,右键单击默认.aspx。选择查看代码

默认.aspx.vb

Note:如果(数据库)表列名包含空格,则需要将其括起来[]。此外,在下面的代码中,图像在加载时会调整大小。最好在将每个图像保存到数据库时调整其大小,这样就不必在每次加载时都调整大小。

Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.IO

Public Class _default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim connectionStr As String = ConfigurationManager.ConnectionStrings("ictsqlConnection").ConnectionString

        Using con As SqlConnection = New SqlConnection(connectionStr)
            'open
            con.Open()

            Using cmd As SqlCommand = New SqlCommand("SELECT [Surplus Id], Department, Category, Item, Visible, TransferableImage FROM Surplus", con)
                Using da As SqlDataAdapter = New SqlDataAdapter(cmd)

                    Dim dt As DataTable = New DataTable()

                    'fill DataTable with data from database
                    da.Fill(dt)

                    'add column that will store the image as a base64 string
                    dt.Columns.Add("TransferableImageBase64", GetType(System.String))

                    For i As Integer = 0 To dt.Rows.Count - 1
                        'convert image Byte() from database to base64 string and store in a new column in the DataTable
                        'dt(i)("TransferableImageBase64") = "data:image/jpg;base64," & Convert.ToBase64String(CType(dt(i)("TransferableImage"), Byte()))

                        'resize image to desired size and convert image Byte() to base64 string, and store in a new column in the DataTable
                        dt(i)("TransferableImageBase64") = "data:image/jpg;base64," & Convert.ToBase64String(ResizeImage(CType(dt(i)("TransferableImage"), Byte()), 50, 50))
                    Next

                    'remove column that contains Byte() from DataTable
                    dt.Columns.Remove("TransferableImage")

                    GridView1.DataSource = dt
                    GridView1.DataBind()
                End Using
            End Using
        End Using
    End Sub
End Class

这是一个演示:


查找 IIS 应用程序池的名称

Win 10:

  • Open 控制面板(查看方式:小图标)
  • 双击管理工具
  • 双击Internet 信息服务 (IIS) 管理器
  • 展开
  • Expand Sites
  • 右键单击所需的网站
  • Select 管理网站
  • Select 高级设置...
  • 写下财产价值Application Pool(例如:ICTSQL)

下面展示了如何添加 IIS 用户(NT AUTHORITY\IUSR)到 SQL Server,如何将其添加到数据库,以及如何授予其对表的权限。 (这假设 SQL Server 和 IIS(Web 服务器)在同一台服务器上运行。您需要为 IIS APPPOOL 用户重复此过程(例如:IIS APPPOOL\ICTSQL)也是如此。

下载/安装 SQL Server 管理工作室 (SSMS) https://learn.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-ver15

创建数据库用户

  • Open 微软 SQL Server 管理工作室
  • Expand Security
  • 右键点击Logins
  • Select 新登录
  • Select Windows 身份验证
  • 登录名:NT AUTHORITY\IUSR
  • 选择所需的默认数据库(例如:ICTSQL)
  • Click OK

将用户添加到数据库

  • Open 微软 SQL Server 管理工作室
  • Expand 数据库
  • 展开(例如:ICTSQL)
  • Expand Security
  • 右键点击Users
  • Select 新用户...
  • 用户名:NT AUTHORITY\IUSR
  • 对于“登录名”,请单击...
  • Click Browse
  • Select NT AUTHORITY\IUSR
  • Click OK
  • Click OK
  • 将“默认架构”留空。
  • Click OK

授予用户对表的权限

  • Open 微软 SQL Server 管理工作室
  • Expand 数据库
  • 展开(例如:ICTSQL)
  • Expand Tables
  • 右键单击(例如:dbo.Surplus)
  • Select 特性
  • 在“选择页面”下,单击权限
  • Click Search
  • Click Browse
  • 检查所需的用户(例如:NT AUTHORITY\IUSR)
  • Click OK
  • Click OK
  • Under Grant,检查以下内容:删除、插入、选择、更新、引用(您可能还想授予:视图更改跟踪、视图定义)
  • Click OK

Note:“With Grant”允许用户将权限授予其他用户。

对“IIS APPPOOL”用户重复上述过程。 (ex: IIS APPPOOL\ICTSQL)

资源:

  • 将连接字符串存储在 Web.config 中 https://www.connectionstrings.com/store-connection-string-in-webconfig/
  • SQL Server 连接字符串 https://www.connectionstrings.com/microsoft-data-sqlclient/
  • 如何在 HTML 中显示 Base64 图像 https://stackoverflow.com/questions/8499633/how-to-display-base64-images-in-html
  • 在 ASP.NET 中使用 RowDataBound 在 gridview 中显示图像 https://stackoverflow.com/questions/29919776/displaying-image-in-gridview-with-rowdatabound-in-asp-net
  • 根据 C# 和 VB.Net 中的列值在 ASP.Net GridView 中分配图像 URL https://www.aspsnippets.com/questions/111703/Assign-Image-URL-in-ASPNet-GridView-based-on-column-value-in-C-and-VBNet/
  • 在 ASP.NET 中绑定 GridView 一步一步 https://www.c-sharpcorner.com/UploadFile/8a67c0/bind-gridview-in-Asp-Net-step-by-step/
  • 使用 MaxHeight 和 MaxWidth 约束按比例调整图像大小 https://stackoverflow.com/questions/6501797/resize-image-proportionally-with-maxheight-and-maxwidth-constraints
  • 如何控制ASP.NET控件在页面中的位置 https://stackoverflow.com/questions/1190359/how-to-control-asp-net-controls-location-in-the-page
  • 在asp.net中创建菜单栏 https://social.msdn.microsoft.com/Forums/en-US/1819233e-113b-4c35-b474-c831eb332cf1/creating-menu-bar-in-aspnet?forum=aspwebforms
  • 选项严格 https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/option-strict-statement
  • 添加 IIS 7 AppPool 身份作为 SQL Server 登录 https://stackoverflow.com/questions/1933134/add-iis-7-apppool-identities-as-sql-server-logons
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Gridview 中显示 varbinary 图像 的相关文章

  • 限制 SQL Server 连接到特定 IP 地址

    我想将 SQL Server 实例的连接限制为特定 IP 地址 我想阻止来自除特定列表之外的任何 IP 地址的任何连接 这是可以在 SQL Server 实例或数据库中配置的东西吗 听起来像是你会使用Windows防火墙 http tech
  • 如何在SSRS 2012中显示基于总金额的前10名

    我只需要显示前 10 名Class基于Total SUM Premium 柱子 我转到类代码属性组 gt 过滤器并按 SUM Net Written Premium 设置前 10 名 但它不起作用 我只需要显示前 10 名 而且总金额也应该
  • aspnetcore 出现角度错误 NodeInitationException:节点调用在 60000 毫秒后超时

    我在用着yo generator aspnetcore spa一旦我运行应用程序 我就遇到了问题 处理请求时发生未处理的异常 NodeIncationException 节点调用在 60000 毫秒后超时 您可以通过设置更改超时持续时间 N
  • 如何在 VS2017/2015 中打开 .xproj 文件

    我有一个带有扩展名的 NET core 项目 xproj 当我在VS 2017中打开项目时 项目文件 xproj migrated to csproj 如何打开 xproj 文件 Visual Studio 2017 2015 我需要安装任
  • 如何检查 ASP.NET Core RC2/1.0 Razor 视图的编译错误?

    Razor 视图预编译已从 RC2 中删除 https github com aspnet Mvc issues 3917 due to 让它在 NET Core 中工作的问题 https github com aspnet Mvc iss
  • 类型或命名空间“MyNamespace”不存在等

    我有通常的类型或命名空间名称不存在错误 除了我引用了程序集 using 语句没有显示为不正确 并且我引用的类是公共的 事实上 我在不同的解决方案中引用并使用相同的程序集来执行相同的操作 并且效果很好 顺便说一句 这是VS2010 有人有什么
  • Amazon RDS for SQL Server 是否支持 SSIS?

    从谷歌搜索中读到一些相互矛盾的答案 不确定答案是是 否还是可能 我觉得读的时候已经很清楚了this http docs aws amazon com AmazonRDS latest UserGuide CHAP SQLServer htm
  • 为什么 SqlClient 在传递 SqlXml 时使用不必要的 XML 转换?

    我有一个关于从 C 代码将 xml 数据类型传递给查询的问题 首先 这是 SQL Server 上的一个表 CREATE TABLE dbo XmlTable id int IDENTITY 1 1 NOT NULL dat xml NOT
  • 比较已编译的 .NET 程序集?

    有没有什么好的程序可以与编译 NET 程序集进行比较 例如 我有 HelloWorld dll 1 0 0 0 和 HelloWorld dll 2 0 0 0 我想比较差异 我该怎么做 我知道我可以使用 NET Reflector 并使用
  • 如何使属性在 POST 请求上必需,但在 PUT 请求上不需要

    假设我有一个用户模型Email and Password用于身份验证目的的属性 如下所示 public class User public long Id get set Required public string FirstName g
  • SELECT 语句会受到 SQL 注入攻击吗?

    实际上有2个问题 我知道我必须尽可能多地使用存储过程 但我想知道以下内容 A 我可以从 SELECT 语句 例如 Select from MyTable 获得 SQL 注入攻击吗 B 另外 当我在 ASP NET 中使用 SQLDataSo
  • 使一个对象只能被同一程序集中的另一个对象访问?

    每个业务对象都有一个包含 sql 调用的匹配对象 我想限制这些 sql 对象 使其只能由匹配的业务对象使用 如何才能实现这一目标 Update 格雷格提出了关于可测试性的观点 由于 SqlObjects 将包含非常特定于业务流程的 sql
  • std::unique_ptr 是否需要知道 T 的完整定义?

    我的标题中有一些代码 如下所示 include
  • 临时表是线程安全的吗?

    我正在使用 SQL Server 2000 它的许多存储过程广泛使用临时表 数据库的流量很大 我担心创建和删除临时表的线程安全性 假设我有一个存储过程 它创建了一些临时表 它甚至可以将临时表连接到其他临时表等 并且还可以说两个用户同时执行存
  • 如何解决 Typescript 构建中的错误“找不到模块 'jquery'”

    我目前在 ts 文件的顶部有这个import require jquery 我这样做是因为我试图在我的打字稿文件中使用 jquery 但我似乎无法编译它 因为它返回标题中所述的错误 我正在使用 ASP NET CORE 脚本文件夹 tsco
  • 在 ASP.NET 5 中使用 DI 调用构造函数时解决依赖关系

    Web 上似乎充斥着如何在 ASP NET 5 中使用 DI 的示例 但没有一个示例显示如何调用构造函数并解决依赖关系 以下只是众多案例之一 http social technet microsoft com wiki contents a
  • SQL - != 'NULL' 的解释

    我的SSMS代码如下 Select top 50 From FilteredContact Where statuscode 1 and emailaddress1 NULL and telephone1 NULL and address1
  • Visual Studio 2010 运行时库

    我编写了一个许多用户会在他们的计算机上使用的工具 但是我注意到 没有安装 Visual Studio 的用户无法打开我的可执行文件 该错误表明 msvcp100 dll 丢失 我在互联网上发现了一个来自微软的可再发行包 它显然应该提供这些
  • Android访问远程SQL数据库

    我可以直接从 Android 程序访问远程 SQL 数据库 在网络服务器上 吗 即简单地打开包含所有必需参数的连接 然后执行 SQL 查询 这是一个私人程序 不对公众开放 仅在指定的手机上可用 因此我不担心第三方获得数据库访问权限 如果是这
  • Visual Studio 2010 中的数据库设计器

    我需要创建一个全新的 Sql Server 2008 数据库 并希望使用 Visual Studio 2010 Ultimate 中的数据库项目 我已经创建了该项目并在下面添加了一个表格dbo架构 桌子 sql仅以纯文本形式显示 但带有颜色

随机推荐

  • 通过右值引用返回是否更有效?

    例如 Beta ab Beta toAB const return move Beta ab 1 1 Beta ab Beta toAB const return move Beta ab 1 1 这会返回一个悬空引用 就像左值引用的情况一
  • 多个鼠标/鼠标/光标?

    如何为多个鼠标显示另一个光标 我有两个 TMemo 两个可以输入各自 TMemo 的键盘 2 个鼠标 我需要 2 个光标 如果假设的话 我已经可以检测出哪只老鼠是哪只 我怎样才能让我自己的光标跟着它一起走 使用德尔福 可能沿着多点 http
  • 使用 bootstrap-datepicker 禁用日期范围?

    如何禁用多个日期范围 使用bootstrap datepicker 目前 这是我关于如何专门禁用日期的代码 div class input group input daterange div
  • Linux shell 编程字符串比较语法

    有什么区别 and 在Linux shell编程中比较字符串 也许下面的代码可以工作 if NAME user then echo your name is user fi 但我认为这不是正确的语法 它将用于比较字符串 陈述 什么是正确的
  • webpack --env.product 和 --mode="product" 之间有什么区别

    如果我错了 请纠正我 但据我从文档中了解到 env option https webpack js org guides environment variables 用来ONLY为了能够在webpack config js如果它导出一个函数
  • 插入表视图并添加按钮或空行时最好的是什么?

    当呈现一个简单的表格视图 或者我想甚至是列表视图 时 您输入新数据的首选方法是什么 With add delete buttons like this Or with a blank line indicating a new record
  • UIAlertViewDelegate 方法 didDismissWithButtonIndex 在手机睡眠/锁定时被调用

    我有一个 UIAlertView 它的 didDismissWithButtonIndex 委托方法调用会弹出视图控制器 同一类 它是 AlertView 委托和视图控制器 以使用户返回到上一个屏幕 问题是 当您在 警报显示 之前锁定手机时
  • Docker 化 Spring boot 应用程序以进行 Kubernetes 部署

    我有一个 Spring Boot 应用程序 在我的 application properties 中具有如下一些属性 server ssl keyStore users admin certs appcert jks server ssl
  • 顺时针旋转数组

    我有一个二维数组 需要顺时针旋转 90 度 但是我不断收到 arrayindexoutofbounds public int rotateArray int arr first change the dimensions vertical
  • ASP.NET Core + IIS + SSL

    如果我想在运行 IIS 作为反向代理的 ASP NET Core 应用程序中使用 https 我是否需要在 IIS 或 ASP NET Core 或两者中配置 SSL 证书 我的计划是在 IIS 上安装证书 这够了吗 在 IIS 上安装证书
  • PHP:数组有最大大小吗?

    PHP 中的数组有限制吗 是的 元素的最大数量有限制 哈希表结构 数组基本上是哈希表的包装器 定义如下 PHP 5 3 typedef struct hashtable uint nTableSize uint nTableMask uin
  • Tensorflow 1.9 / 对象检测:model_main.py 仅评估一张图像

    我已更新到 Tensorflow 1 9 和对象检测 API 的最新版本 当运行以前运行良好的训练 评估会话时 我认为版本 1 6 训练似乎按预期进行 但我只获得一个图像 第一个图像 的评估和指标 在 Tensorboard 中 图像标记为
  • 为什么结构体数组比较有不同的结果

    我不知道为什么会发生以下情况 而且我找不到相关的源代码 有人能给我解释一下吗 var s ss struct two empty structs arr1 6 struct s array with empty struct pointer
  • Python/MySQL 查询错误:“未知列”

    该脚本旨在充当命令行前端 将记录添加到本地托管的 MySQL 数据库 我收到此错误 mysql connector errors ProgrammingError 1054 42S22 Unknown column watermelon i
  • 将 64 位数组转换为 Int64 或 ulong C#

    我有一个 int 数组 长度始终为 64 例如 1110000100000110111001000001110010011000110011111100001011100100 我想把它写成一篇Int64 或ulong 变量 怎么做 我尝试
  • Python 中某些坐标处的二维高斯拟合强度

    我有一组坐标 x y z x y 它们描述坐标 x y 处的强度 z 对于不同坐标处的一组强度 我需要拟合一个二维高斯函数来最小化均方误差 数据位于 numpy 矩阵中 对于每个拟合会话 我将有 4 9 16 或 25 个坐标 最终我只需要
  • Chrome 违规:[违规] 处理程序花费了 83 毫秒的运行时间

    我正在尝试在我的项目中实现 Facebook 的注销功能 登录效果很好 但我面临着在 JavaScript 控制台中使用注销代码获取以下消息 违规 长时间运行的 JavaScript 任务花费了 318 毫秒 session php 51
  • Gradle 跳过 jacoco 覆盖率插件

    我知道在 stackexchange 上有很多类似的问题 但这让我发疯 任何其他答案都没有帮助我 我几乎使用了我能找到的所有 gradle 强制标志 我的 Gradle 版本是 2 2 1 我的构建 gradle buildscript e
  • 有人可以解释一下 Ektorp 中的 Cascading 和 FetchType 惰性吗?

    我是 CouchDB 和 Ektorp 的新手 实际上我今天就开始尝试使用它 我找到的帮助我入门的最详细的文档是这个 http www ektorp org reference documentation html d100e394 htt
  • 在 Gridview 中显示 varbinary 图像

    更新 表定义 ICTSQL 中的表名称剩余 Windows 身份验证 剩余ID int 部门nchar 50 类别 nchar 25 项目 nchar 75 可见位 TransferableImage varbinary MAX 我有一个