imageTest table
---------------
imgName ( varchar )
contentType ( varchar )
data ( varbinary(max) )
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<br />
<br />
<br />
<asp:Image ID="Image1" runat="server" />
</div>
</form>
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.IO
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim strCon As String = ConfigurationManager.ConnectionStrings("ConnectionString1").ConnectionString
Dim con As New SqlConnection(strCon)
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandType = CommandType.Text
Dim strSelect As String = "SELECT * FROM [imageTest] WHERE [id] = 1"
cmd.CommandText = strSelect
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader() 'must be after con.open()
If (reader.Read()) Then 'must include for reader
Label1.Text = reader(0).ToString
Label2.Text = reader(1).ToString()
reader.Close()
con.Close()
End If
End Sub
End Class
数据库是SQL Server。图像而不是图像路径在数据库中存储为varbinary(max)
。
如何显示数据库中的图像以及其他控件,例如labels
和textboxes
,其内容也从数据库中检索?
我已经看过并尝试了一些教程,但它们要么在C#
中,要么不起作用,或者向您展示如何仅显示图像,或者在gridview
中显示图像。
欢迎使用示例代码。
答案 0 :(得分:0)
首先,您必须在我们的解决方案中创建图像文件夹 之后写这个方法
public static int imageupload(string imagename,string imagepath)
{
var value = 0;
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
//Open the database connection
con.Open();
//Query to insert images path and name into database
SqlCommand cmd = new SqlCommand("Insert into imagetable(imagename,image) values(@imagename,@image)", con);
//Passing parameters to query
cmd.Parameters.AddWithValue("@imagename",imagename);
cmd.Parameters.AddWithValue("@image", imagepath);
cmd.ExecuteNonQuery();
value = 1;
//Close dbconnection
con.Close();
}
catch(Exception ex)
{
throw ex;
}
return value;
}