Hello and thanks for taking a moment. I am trying to retrieve and display an image that is stored in SQL Server 2000. My aspx code is as follows:
<HTML>
<HEAD>
<title>photoitem</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:DataGrid id="DataGrid3" HorizontalAlign='Left' runat="server" AutoGenerateColumns="true"
Visible="True">
<Columns>
<asp:TemplateColumn HeaderText="Image">
<ItemTemplate>
<asp:Image
Width="150" Height="125"
ImageUrl='<%# FormatURL(DataBinder.Eval(Container.DataItem, "InventoryItemPhoto")) %>'
Runat=server />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</form>
</body>
</HTML>
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------My code behind file is below VS 2003 does not like my datareader. It says the following:
'System.Data.SqlClient.SqlDataReader' does not contain a definition for 'Items'
If there are any suggestions as to what I am doing wrong I would appreciate the input. - Jason
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text;
namespace ActionLinkAdHoc
{
/// <summary>
/// Summary description for photoitem.
/// </summary>
public class photoitem : System.Web.UI.Page
{
string connStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
protected System.Web.UI.WebControls.DataGrid DataGrid3;
private void Page_Load(object sender, System.EventArgs e)
{
// Get the querystring ID
string item =Request.QueryString["ID"];
int ID=Convert.ToInt32(item);
SqlConnection dbConn5 = new SqlConnection(connStr);
SqlCommand sqlCom5 =new SqlCommand("sp4TWRetrieveItemPhotos");
sqlCom5.Connection = dbConn5;
sqlCom5.CommandType = CommandType.StoredProcedure;
sqlCom5.Parameters.Add("@ID", SqlDbType.Int);
sqlCom5.Parameters["@ID"].Value =ID;
dbConn5.Open();
SqlDataReader myDataReader;
myDataReader = sqlCom5.ExecuteReader(CommandBehavior.CloseConnection);
DataGrid3.DataSource = sqlCom5.ExecuteReader();
DataGrid3.DataBind();
while(myDataReader.Read())
{
Response.ContentType = myDataReader.Items("JPEG");
Response.BinaryWrite(myDataReader.Items("InventoryItemPhoto"));
}
dbConn5.Close();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}
Hello and thanks for taking a moment. I am trying to retrieve and display an image that is stored in SQL Server 2000. My aspx code is as follows:<HTML> <HEAD> <title>photoitem</title> <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> <asp:DataGrid id="DataGrid3" HorizontalAlign='Left' runat="server" AutoGenerateColumns="true" Visible="True"> <Columns> <asp:TemplateColumn HeaderText="Image"> <ItemTemplate> <asp:Image Width="150" Height="125" ImageUrl='<%# FormatURL(DataBinder.Eval(Container.DataItem, "InventoryItemPhoto")) %>' Runat=server /> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:DataGrid> </form> </body></HTML>-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------My code behind file is below VS 2003 does not like my datareader. It says the following: 'System.Data.SqlClient.SqlDataReader' does not contain a definition for 'Items'If there are any suggestions as to what I am doing wrong I would appreciate the input. - Jasonusing System;using System.Collections;using System.ComponentModel;using System.Data;using System.Drawing;using System.Web;using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HtmlControls;using System.Data.SqlClient;using System.Text;namespace ActionLinkAdHoc{ /// <summary> /// Summary description for photoitem. /// </summary> public class photoitem : System.Web.UI.Page { string connStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]; protected System.Web.UI.WebControls.DataGrid DataGrid3; private void Page_Load(object sender, System.EventArgs e) { // Get the querystring ID string item =Request.QueryString["ID"]; int ID=Convert.ToInt32(item); SqlConnection dbConn5 = new SqlConnection(connStr); SqlCommand sqlCom5 =new SqlCommand("sp4TWRetrieveItemPhotos"); sqlCom5.Connection = dbConn5; sqlCom5.CommandType = CommandType.StoredProcedure; sqlCom5.Parameters.Add("@ID", SqlDbType.Int); sqlCom5.Parameters["@ID"].Value =ID; dbConn5.Open(); SqlDataReader myDataReader; myDataReader = sqlCom5.ExecuteReader(CommandBehavior.CloseConnection); DataGrid3.DataSource = sqlCom5.ExecuteReader(); DataGrid3.DataBind(); while(myDataReader.Read()) { Response.ContentType = myDataReader.Items("JPEG"); Response.BinaryWrite(myDataReader.Items("InventoryItemPhoto")); } dbConn5.Close(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion }}
As part of a web site I allow users to store documents in SQL Server 2000 using an Image column on a table. After the file is saved the user can open the document through the browser. This works great for most file extensions such as ".XLS" or ".DOC" but fails when attempting to open ".MSG" files (saved outlook messages). XLS documents will open in Excel and DOC documents open in Word, but MSG documents open in Notepad and display what appears to be binary data. I'm trying to figure out if this is a SQL Server issue or some sort of ASP/ASP.NET webserver issue.
If I attempt to open an MSG file stored directly on the web server, the file opens correctly using the "Microsoft Outlook View Control", but when attempting to open the same file saved in SQL Server, it attempts to open in notepad.
Ok, again, I'm reasonably new to this. I've been trying to display an image stored in SQL in a ASP.NET page. Pretty simple stuff I would have thought. I've read countless examples of how to do this online, and many of them use the same method of displaying the image, but none seem to work for me. The problem seems to lie in the following line of code: Dim imageData As Byte() = CByte(command.ExecuteScalar())Which always returns the error: Value of type 'Byte' cannot be converted to '1-dimensional array of Byte'.Here's the rest of my code, hope someone can help. It's doing my head in! Imports System.Data.SqlClient Imports System.Data Imports System.Drawing Imports System.IOPartial Class _ProfileEditor Inherits System.Web.UI.PageProtected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'Get the UserID of the currently logged on user Dim NTUserID As String = HttpContext.Current.User.Identity.Name.ToString Session("UserID") = NTUserID Dim Photo As Image = NothingDim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString) Dim command As SqlCommand = connection.CreateCommand() command.CommandText = "SELECT Photograph, ImageType FROM Users WHERE UserID = @UserID"command.Parameters.AddWithValue("@UserID", NTUserID) connection.Open()Dim imageData As Byte() = CByte(command.ExecuteScalar())Dim memStream As New MemoryStream(Buffer) Photo = Image.FromStream(memStream) End Sub End Class
Dear Friends, I have read many solution over the net, but since I am unable to utilize anyone according to my needs I am seeking help from you people. I have a table imagedata in sql server 2005 having fields name and imageperson. Name is string and imageperson is Image field. I have successfully stored name of the person and his image in database. I have populated the dataset from codebehind and bind it to the repeater. By writing <%# DataBinder.Eval(Container.DataItem, "name")%>I am a able to retrieve the name of the person. But when I pass photodata as <%#photogen((DataBinder.Eval(Container.DataItem, "imageperson")))%> where photogen is function in code behind having structure public void photogen(byte[] dataretrieved) { Response.BinaryWrite(datarerieved) } But it is giving error at <%#photogen((DataBinder.Eval(Container.DataItem, "imageperson")))%> The best overloaded method match for '_Default.photogen(byte[])' has some invalid arguments AND Cannot convert object to byte[]. Can anyone please provide me working solution with code for aspx page and code behind. Thanks and regards
I have a SQL database that has Images stored. I am able to read the image from the database and display it. But i am not able to control the size and the position where it is displayed. I want to develop something like a photo album. the images should be displayed in a smaller size. but when the user clicks on the image, it should blow up to its original size. I am struggling with this for some time. Any suggestions as how to develop it??. Any help in this regard would be highly appreciated.
i am trying to retrieve an image blob stored in SQL to a web matrix form (using VB.NET). I am totaly new to this and i got the code below from a site but it doesn't see to work..... <%@ Page Language="VB" %> <%@ import Namespace="System.Data" %> <%@ import Namespace="System.IO" %> <%@ import Namespace="System.Drawing.Image" %> <%@ import Namespace="System.Drawing.Bitmap" %> <%@ import Namespace="System.Drawing.Graphics" %> <%@ import Namespace="System.Web.UI.WebControls" %> <%@ import Namespace="System.Data.Odbc" %> <%@ import Namespace="System.Data.SqlClient" %> <script runat="server"> Private Function GetImageFromDB(ByVal ImageID As Integer) As System.Drawing.Image
' Get the Connection string Dim strConnection As String strConnection = "server='(local)'; trusted_connection=true; database='mydatabasename'"
Dim conn As New SqlConnection(strConnection) Dim sqlCommand As String Dim strImage As String Dim image As System.Drawing.Image
Try sqlCommand = "SELECT ImageField FROM ImageTable WHERE MyImageId = " + ImageID.ToString
Dim cmd As New SqlCommand(sqlCommand) cmd.Connection = conn conn.Open() Dim dr As SqlDataReader dr = cmd.ExecuteReader() While (dr.Read())
Dim byt As Byte() byt = dr.Item(strImage) Dim bmp As New System.Drawing.Bitmap(New System.IO.MemoryStream(byt)) image = bmp
End While Catch ex As Exception ' Log Error Response.Write(ex.Message) Finally If conn.State = ConnectionState.Open Then conn.Close() End If End Try
Return image
End Function
Private Sub Page_Load (ByVal sender As System.Object, ByVal e As System.EventArgs) If Not IsPostBack Then GetImageFromDB(2111) End If End Sub </script> <html> <head> </head> <body> <form enctype="multipart/form-data" runat="server"> <asp:Image id="BrandSignImg" runat="server"></asp:Image> </form></body></html>
I have an employee directory application that displays employees in a gridview. When a record is selected, a new page opens and displays all info about the employee, including their photo. I have the code working that displays the photos, however, when no photo is present an exception is thrown that "Unable to cast object of type System.DbNull to System.Byte[]". I'm not sure how to test for no photo before trying to write it out. My code is as follows (with no error trapping): Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load, Me.Load Dim temp As String Dim connPhoto As System.Data.SqlClient.SqlConnection Dim connstring As Stringconnstring = Web.Configuration.WebConfigurationManager.ConnectionStrings("connPhoto").ConnectionString connPhoto = New System.Data.SqlClient.SqlConnection(connstring)temp = Request.QueryString("id") Dim SqlSelectCommand2 As System.Data.SqlClient.SqlCommand Dim sqlstring As String sqlstring = "Select * from dbo.PhotoDir WHERE (CMS_ID = " + temp + ")"SqlSelectCommand2 = New System.Data.SqlClient.SqlCommand(sqlstring, connPhoto) Try connPhoto.Open()Dim myDataReader As System.Data.SqlClient.SqlDataReader myDataReader = SqlSelectCommand2.ExecuteReader Do While (myDataReader.Read()) Response.BinaryWrite(myDataReader.Item("ImportedPhoto")) Loop connPhoto.Close()Catch SQLexec As System.Data.SqlClient.SqlException Response.Write("Read Failed : " & SQLexec.ToString()) End TryEnd Sub End Class
I am using the 3-tiered architecture design (presentation, business laws, and data acess layers). I am stuck on how to send the image the user selects in the upload file control to the BLL and then to the DAL because the DAL does all the inserts into the database. I would like to be able to check the file type in the BLL to make sure the file being uploaded is indeed a picture. Is there a way I can send the location of the file to the BLL, check the filetype, then upload the file and have the DAL insert the image into the database? I have seen examples where people use streams to upload the file directly from their presentation layer, but I would like to keep everything seperated in the three classes if possible. I also wasn't sure what variable type the image would be in the function in the BLL that receive the image from the PL. If there are any examples or tips anyone can give me that would be appreciated.
Hay Friend's Can u plese send me the way how to save image in sql server and display that images in datagrid or other control also like Image control or Image control Button?? Plese send the coding in C#. Thank's Amit
Ok, the problem is that , i have a field called "Attach" in sql of type image, when selecting it , the field is getting data of type BYTE(). which am being unable to display them on an Image on the panel.
using the following vb.net code:
'Dim sel2 As String
'Dim myCom As SqlCommand
'Dim conn As New SqlConnection
'Dim drr As SqlDataReader
'Dim image As System.Drawing.Image
'sel2 = "select * from attach where att_desc = '" & DropDownList1.SelectedItem().Text & "' and doc_code = " & w_doc_code & " and subcode = " & w_doc_subcode & " and doc_num= " & w_doc_num & " "
I have learned lots of informative thing from your forums. I have little problem regarding “Display image from SQL Server on ASP.NET� I have done it and image display on my page from SQL Server. I have cleared you here I have adopt two different methods which are following for displaying picture.
but in both above methods I have faced little problem when image display on my page all other information can not display and I also want to display picture on my specific location on the page. My second question is can use any web control like “Image1� to display image from SQL Server where my pictures are stored.
hi,i have inserted the image present in mydocuments using alter commandcreate table aa(a int, d image)insert into aa values (1,'F:prudhviaba 002.jpg')when i doselect * from aai am getting the result in the column d as0x463A5C707275646876695C70727564687669203030322E6A 7067how i can i view the image?pls clarify my doubtsatish
In my asp.net application I have a local report with an image control in thedetail row of the table and the Value attribute set as="File://" & Fields!FQPhotoFileName.ValueThe first row in the table always shows the wrong image and it's always thesame wrong image. The problem is there even when I change the sort order orthe criteria for the underlying dataset. For example, I ran a small testthat populated the dataset with 2 rows and 2 images. When I sort by anycolumn (e.g. ID) in ascending ascending order the ID=1 row (the 1st row)shows the wrong image and the ID=2 row shows the correct image. When I rerunthe report sorting in descending order the ID=2 row (which is now the 1strow) shows the wrong image and the ID=1 shows the correct image.Any suggestions?
Hi, I have a website and i am uploading the gif image to the database. i have used varchar(500) as the datatype and i am saving the file in the webserver so the path to it c:intepub....a.gif
my upload table has the folliwing feilds UploadId Int Identity, Description, FileName, DiskPath varchar(500), weblocation varchar(500). I have a main sproc for the report where i am doing a inner join with other table to get the path of the gif..
So my question is how can i get a picture to show up on the report. . What kinda datatype the gif file should be stored in the database? If it is stored as a varchar how can i access it and what is best way to reference that particular.
I have inherited a VS 2005 database with a table that has a column of type IMAGE. I need to change the image for one of the rows in the table. I have the new image in a *.PNG file on my C: drive. What is the correct method for inserting this file into the IMAGE column.
I am storing data as binary in my sql server 2000 database, and now I wanted to retrieve the data- before I move on I just wanted to check whether the data is restored correctly. Is there an easy way for that? A tool for sql 2000 or any other simple options?
Please HELP! On my asp.NET page I'm setting a datetime variable to Now() and inserting that value into SQL Server as a datetime stamp. I want to then retrieve the count of the number of records that were inserted into the table that have that value. The field in the table is just a datetime datatype.But it's returning 0 records because the Now() value is getting converted to military time and losing the seconds! For example, Now() is "9/13/2005 2:48:25 PM" but the value being inserted into the table is "2005-09-13 14:48:00.000".ARRRGGHH! What am I missing?? What do I need to do to be able to (1) keep the seconds, and (2) identify the records in order to retrieve them?Thanks in advance for your help!!!Lynnette
I have a login name being displayed when a user logs in, like so: "Welcome: johndoe23"This is displayed through the use of the <asp:LoginName> tag.I want to do a query on the database that only selects data relevant to that userName and wish to assign that logged in username to a variable so we can use an SQL command similar to: "SELECT something WHERE userID=" + loggedInUserName;
hy all..How can I achieve the above ?Moreover can I retrieve data from multiple databases which are lying on different DBMSs ( like retrieving from database A which is on SQL and from database B which is on Oracle ) ?Rgds.
We have a domain where all computers are on GMT(Greenwitch Mean Time). We have an access front end that timestamps certain fields according to the client time that the program is running on, but we will be moving our client workstations off of GMT time and keep our SQL Server on GMT time, and want to keep the timestamps GMT.
So, I wanted to know if it was possible to create a stored procedure that gets the Server's time and returns it to the Access frontend for entry into the timestamp fields?
Or, if anyone has a better idea of how to get the time from the server to use on the clients, I would greatly appreciate it!!!
I use the following SQL to set up a linked server with Excel and attempt to retrieve data. The c: empauthors.xls is downloaded from the second page of the article above.
EXEC sp_addlinkedserver 'EXCEL', 'Excel', 'Microsoft.Jet.OLEDB.4.0', 'c: empauthors.xls', NULL, 'Excel 8.0', NULL GO SELECT * FROM EXCEL...Sheet1$ GO
The query sets up the linked server OK, and retrieves the field names, but no data is returned. The results in Management Studio are a list of column names:
au_id au_lname au_fname phone address city state zip contract
then an error:
OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "EXCEL" returned message "Unknown". Msg 7321, Level 16, State 2, Line 1 An error occurred while preparing the query "SELECT `Tbl1002`.`au_id` AS `Col1004`,`Tbl1002`.`au_lname` AS `Col1005`,`Tbl1002`.`au_fname` AS `Col1006`,`Tbl1002`.`phone` AS `Col1007`,`Tbl1002`.`address` AS `Col1008`,`Tbl1002`.`city` AS `Col1009`,`Tbl1002`.`state` AS `Col1010`,`Tbl1002`.`zip` AS `Col1011`,`Tbl1002`.`contract` AS `Col1012` FROM `Sheet1$` `Tbl1002`" for execution against OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "EXCEL".
Does anyone know how to resolve this? I'm using Windows Authentication to connect to a SQL server (9.0.3054) instance on localhost, and am running from a test database query window.
Question in review today is Creating a Report showing the FName, LName of all Employees not Specified in a region; I would assume "No Value to be Null" Correct?
Or is there another way for me to do this?
This is what I have so far...What am I missing that this is not showing me results?
Select Firstname, Lastname, Region From Employees WHERE Region LIKE 'null%';
I have created stored procedures and I am checking whether any error has occured on execution of the statements in that procedure.
If the @@Error <>0 then I need to log this error into my error logging table. For this, I need to retrieve the error description given by SQL SERVER 2000.
I tried this using the master.dbo.sysmessages table. But I get a text from master.dbo.sysmessages which has the placeholders like %l, %s, etc.
I dont want this type of error. I want the exact error description which has the actual objects names and not the placeholders.
I found some help at this link : http://www.sommarskog.se/error-handling-I.html#textretrieve
But i want to know whether there is any other way of doing this or not.
Hi There, Can I store flash files in the database. I have a table with one of the columns as varbinary datatype. Previously, I was saving images (as filebytes) into this column. But now I need to implement something to store the flash file. So, is it possible to store flash files in the database and retrieve them and display them in an asp.net page? Thanks a lot for your suggestion!!
Currently i am defining a simple relationship between Customers->Orders->Order Details through the Database Diagrams feature in the SQL 2K. Using the Server Explorer, i can see the Database Diagrams, but when i try to "drop" the Database Diagrams into the page, it gives the error message.
I would like to know the procedures to retrieve the database relationships from Database Diagrams and manipulate them through ADO.NET
I prefer to "convert" already defined relationship using SQL Server Database Diagrams into XSD file or probably there is another method to "read" those relationship and manipulate them.
I have a drop down menu for transmission. Inside the drop down menu, there are 1.Any 2.Auto 3.Manual options
Now I want to retrieve from my database, if the client select '1.Any' option. Meaning the output I want it to display all the products which have both auto and manual for transmission.
I have no problem retrieving all the products which either only have auto option or manual option.
( select min(cast(f.valuestr as float)) from bvfindings f where f.ObjectName = 'Hematocrit' and f.sessionid = s.sessionid and f.ValueTime > s.open_time)
the above returns me the 10.9
i modified the query
select min(cast(f.valuestr as float)), f.valuetime from bvfindings f where f.ObjectName = 'Hb'
I'm at loss how I'm supposed to work with typed datasets and Sql Server Compact 3.5, when inserting records and I need to update my datatables with the primary key of newly inserted rows.
I've tried adding a RowUpdated handler to all tableadapters that look like this:
I've previously used this type of approach when working with an OleDbDatabase, which works just fine. But it doesn't work with Sql Server CE 3.5, and since it doesn't support stored procedures I can't fix it that way either. And it doesn't support commands in a batch (i.e appending the Insert command of the adapter with ";SELECT @@IDENTITY") so that doesn't work either...
So how are we supposed to use Sql Server CE 3.5? It's impossible together with datasets? Or am I missing something obvious?
Some T-SQL commands can fail with multiple errors. For example, if you try to disable a primary key constraint using ALTER TABLE t1 NOCHECK CONSTRAINT PK, you will get messages like:
Msg 11415, Level 16, State 1, Line 341 Object 'PK' cannot be disabled or enabled. This action applies only to foreign key and check constraints. Msg 4916, Level 16, State 0, Line 341 Could not enable or disable the constraint. See previous errors.
However, in the code below, only the last message is printed. How can I print all the error messages?
USE tempdb; CREATE TABLE #t1(c1 INT CONSTRAINT PK PRIMARY KEY); BEGIN TRY ALTER TABLE #t1 NOCHECK CONSTRAINT PK; PRINT 'Primary key disabled' END TRY BEGIN CATCH PRINT ERROR_MESSAGE(); END CATCH