Reload GridView or Repeater on AjaxFileUpload UploadComplete Event in ASP.NET - asp.net

Hi is there anyway to update (Gridview or Repeater data) after AjaxFileUpload UploadComplete Event. What I want to do is upload multiple picture using AjaxFileUpload and once the files are uploaded it should display those pictures into a GridView or Repeater control.
I could not do this unless a button click event is fired.
Any ideas???

Put hidden button onto a form and attach this function to OnClientUploadComplete event handler of extender
<asp:Button runat="server" ID="HiddenButton" OnClick="RefreshGridView" style="display:none;" />
function uploadComplete(sender, args) {
for (var index = 0; index < sender._filesInQueue.length; ++index) {
if (!sender._filesInQueue[index]._isUploaded) {
return;
}
}
__doPostBack("<%= HiddenButton.UniqueID %>", "");
})
then, refresh your GridView on this button's click.

This code checks for the file that's uploaded, creates an email with the file information, emails the person the file was intended for with a link. It also stores all the info into a database. On the upload page is a gridview that lists all the files that have been uploaded. It updates after the files is loaded. I think you can get what you need out of it.
Partial Class upload_Default
Inherits System.Web.UI.Page
Protected Sub UploadButton2_Click(sender As Object, e As EventArgs)
Dim fileGuid As String
fileGuid = Guid.NewGuid.ToString
If AsyncFileUpload1.HasFile Then
If AsyncFileUpload1.FileContent.Length < 20971500 Then
Try
Dim fileSizeB As Integer = AsyncFileUpload1.PostedFile.ContentLength
Dim fileSize = fileSizeB / 1024
Dim filename As String = Path.GetFileName(AsyncFileUpload1.FileName)
Dim fileNameTwo As String = Trim(fileGuid) + Trim(filename)
Dim ExistPdfFilenamOPO As String
ExistPdfFilenamOPO = Server.MapPath("~/uploads/files/") & filename
If File.Exists(ExistPdfFilenamOPO) Then
Label2.Text = "File is already there"
Else
Dim saveDir As String = "\Uploads\files\"
Dim appPath As String = Request.PhysicalApplicationPath
Dim savePath As String = appPath + saveDir + _
Server.HtmlEncode(AsyncFileUpload1.FileName)
AsyncFileUpload1.SaveAs(savePath)
UploadStatusLabel2.Text = "Upload status: File uploaded."
Label2.Text = ""
' Email
Dim sr As New StreamReader(appPath & "EmailTemplates/FileUpload.htm")
Dim FName As String = TextBoxFName.Text
Dim LName As String = TextBoxLName.Text
Dim Email As String = TextBoxEmail.Text
Dim fullPath As String
fullPath = "https://website.com/uploads/default.aspx?fileGuid=" + fileGuid
Dim message As New MailMessage()
message.IsBodyHtml = True
message.From = New MailAddress("Your email")
message.[To].Add(New MailAddress(Email))
message.Subject = "The file you requested from SRTR"
message.Body = sr.ReadToEnd()
sr.Close()
message.Body = message.Body.Replace("<%FName%>", FName)
message.Body = message.Body.Replace("<%LName%>", LName)
message.Body = message.Body.Replace("<%Email%>", Email)
message.Body = message.Body.Replace("<%FileName%>", filename)
message.Body = message.Body.Replace("<%VerificationUrl%>", fullPath)
Dim client As New SmtpClient()
client.Send(message)
'Insert in to t_UploadFiles
Dim datenow As Date = System.DateTime.Now()
Dim ExDate As Date = datenow.AddDays(15)
Dim Downloaded As Boolean = False
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim updateSql As String = "INSERT t_UploadFiles (FileGuid, FileName, FileSize, FName, LName, Email, UploadDate, ExDate, Downloaded) SELECT #FileGuid, #FileName, #FileSize, #FName, #LName, #Email, #UploadDate, #ExDate, #Downloaded"
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(updateSql, myConnection)
myCommand.Parameters.AddWithValue("#FileGuid", fileGuid.Trim())
myCommand.Parameters.AddWithValue("#FileName", filename.Trim())
myCommand.Parameters.AddWithValue("#FileSize", fileSize)
myCommand.Parameters.AddWithValue("#FName", FName.Trim())
myCommand.Parameters.AddWithValue("#LName", LName.Trim())
myCommand.Parameters.AddWithValue("#Email", Email)
myCommand.Parameters.AddWithValue("#UploadDate", datenow)
myCommand.Parameters.AddWithValue("#ExDate", ExDate)
myCommand.Parameters.AddWithValue("#Downloaded", Downloaded)
myCommand.ExecuteNonQuery()
myConnection.Close()
End Using
articleListXX.DataBind()
End If
Catch ex As Exception
UploadStatusLabel2.Text = "Upload status: The file could not be uploaded.<br/>The following error occured: " + ex.Message
End Try
Else
UploadStatusLabel2.Text = "File is too large."
End If
Else
UploadStatusLabel2.Text = "You did not specify a file to upload."
End If
End Sub
End Class

Ok guys thanks for your contribution and sorry for making my query a bit unclear. I finally figured it out but only because of your ideas. Here is my code. The same applies to gridview. The main purpose is to use AjaxFileUpload control to upload pictures and on OnUploadComplete="AjaxFileUpload1_UploadComplete" event call the method for creating thumbnail image. Once thumbnails are created the method populatePic() is call to populate thumbnail images into a repeater control with the help of javascript _doPostBack() method without the needs of firing a button by the user.
<script type="text/javascript">
function showUploadedPic()
{
__doPostBack('btnAdd', null);
}
</script>
<cc1:AjaxFileUpload ID="AjaxFileUpload1" runat="server" OnUploadComplete="AjaxFileUpload1_UploadComplete" ThrobberID="myThrobber" MaximumNumberOfFiles="10" AllowedFileTypes="jpg,jpeg" OnClientUploadComplete="showUploadedPic" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl="<%# Container.DataItem %>" height="100"/>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Code Behind
protected void btnAdd_Click(object sender, EventArgs e)
{
populatePic();
}
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string filePath = Server.MapPath("~/files/") + e.FileName;
AjaxFileUpload1.SaveAs(filePath);
createThumbnail();
}

Below code is tested and works.
<asp:Button runat="server" ID="HiddenButtonFileUpload"
OnClick="RefreshGridView" style="display:none;" />
<ajax:AjaxFileUpload ID="AjaxFileUpload11" runat="server"
MaximumNumberOfFiles="3" AllowedFileTypes="txt,xls,xlsx,doc,docx,pdf"
Width="400px"
OnUploadComplete="OnUploadComplete"
OnClientUploadStart="UploadStart" OnClientUploadCompleteAll="UploadComplete"
ClearFileListAfterUpload="true" />
function UploadComplete() {
unblock();
__doPostBack("<%= HiddenButtonFileUpload.UniqueID %>", "");
}
Code Behind :
protected void RefreshGridView(object sender, EventArgs e)
{
BindForm(); // refresh your gridview
}

Related

how to check the duplicate filename in asp:fileupload?

i have an updatepanel and inside of it the contenttemplate is an asp:FileUpload..now when i will try to choose the file i want to check the filename in the database..i know my database part but how will i call the function in the server like for asp:TextBox i can use OnTextChanged something like that..but for asp:FileUpload is there anything by which i can check the filename and without clicking the button add?? my code
<asp:UpdatePanel runat="server" ID="fileupdatepanel">
<ContentTemplate>
<asp:FileUpload ID="tutorialupload" runat="server" AutoPostBack="true" OnLoad="filename_Changed" />
<asp:Label runat="server" ID="f1"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="addbttu" runat="server" Text="Add" OnClick="addtutorial_Click" />
my aspx.cs code
protected void filename_Changed(object sender, EventArgs e)
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
string tuname = tutorialupload.PostedFile.FileName;
tuname = tuname.Substring(0, tuname.LastIndexOf("."));
SqlCommand objcmd = new SqlCommand("Select tutorialid from tutorialtable where tutorialname='" + tuname + "'", objsqlconn);
SqlDataReader grpIDreader = objcmd.ExecuteReader();
grpIDreader.Read();
if (grpIDreader.HasRows)
{
f1.Text = "Duplicate filename.Sorry.";
}
else
{
f1.Text = "";
}
objsqlconn.Close();
}
now when i will choose the file..i want to call this function filename_Changed() and it will give me the result whether the filename is present or not..so i want to do it without clicking my the add button??
You should use the has file property, when true do you DB check, something like this
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
// Before attempting to save the file, do something
else
// Notify the user that a file was not uploaded.
UploadStatusLabel.Text = "You did not specify a file to upload.";
}
Here is how you can detect the change in the selected file name using JavaScript through the FileUpload onChange event.
ASPX Page: Make sure to set EnablePageMethods = true in the ScriptManager object.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="fileupdatepanel">
<ContentTemplate>
<asp:FileUpload ID="tutorialupload" runat="server" OnChange="CheckFileName(this)" />
<asp:Label runat="server" ID="f1"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="addbttu" runat="server" Text="Add" OnClick="addtutorial_Click" />
JavaScript:
function CheckFileName(oFile)
{
PageMethods.FileNameChecker(oFile.value, OnSucceeded);
}
function OnSucceeded(result, userContext, methodName)
{
lbl = document.getElementById('<%=f1.ClientID %>');
if (methodName == "FileNameChecker")
{
if (result == true)
{
lbl.innerHTML = 'Duplicate filename.Sorry.';
lbl.style.color = "red";
}
else
{
lbl.innerHTML = '';
}
}
}
C# Code-Behind: You can call a WebMethod to check if the new selected filename exists in the DB:
You need to reference the following:
using System.Web.Services;
Then add the following method and make sure you put [WebMethod] before method declaration:
[WebMethod]
public static bool FileNameChecker(string newFileName)
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
string x = newFileName.Substring(0,newFileName.LastIndexOf("\\"));
string tuname = newFileName.Substring(newFileName.LastIndexOf("\\") + 1, newFileName.Length - x.Length - 1);
tuname = tuname.Substring(0, tuname.LastIndexOf("."));
SqlCommand objcmd = new SqlCommand("Select tutorialid from tutorialtable where tutorialname='" + tuname + "'", objsqlconn);
SqlDataReader grpIDreader = objcmd.ExecuteReader();
grpIDreader.Read();
bool found = false;
if (grpIDreader.HasRows)
found = true;
objsqlconn.Close();
return found;
}

display image from db in image control, alongside other asp.net controls

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
Database is SQL Server. The image, and not the image path, is stored as varbinary(max) in the db.
How do I display a image from the db, alongside other controls such as labels and textboxes whose content are also retrieve from the db?
I have seen and try a number of tutorials but they either in C#, or doesn't work, or show you how to display an image only, or display the image in a gridview.
Sample codes are most welcome.
first you have to create image folder in our solution
after that writ this method
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;
}
protected void Button1_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(fileuploadimages1.PostedFile.FileName);
fileuploadimages1.SaveAs(Server.MapPath("Images/" + filename));
int a = testapp.imageupload(TextBox1.Text, "Images/" + filename);
if(a==1)
{
Response.Write(#"<script language='javascript'>alert('saved secussfully')</script>");
Response.Redirect("home.aspx");
}
else
{
Response.Write(#"<script language='javascript'>alert('error whie saving image')</script>");
}
}

How to refresh Gridview after pressed a button in asp.net

I am trying to make a simple library database. I list the search results in a gridview, then i have a textbox and a button, user enters the isbn and clicks loan button. Then, if there is enough number of items (itemNumber>0) it is loaned by user. Here is the screenshot of user interface:
My question is, when user clicks loan button the loan may or may not be succesful. In both cases, i print a message indicating whether loan is succesful or not, and i also want the updated gridview to be displayed. The problem is, after pressing the loan button the gridview disappears and i just see the textbox, button and the message on the screen. How can i show the updated version of gridview after pressing loan button?
Here is the code file:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SearchResults.aspx.cs" Inherits="Pages_SearchResults" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ISBN" DataSourceID="SqlDataSource1"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="ISBN" HeaderText="ISBN" ReadOnly="True"
SortExpression="ISBN" />
<asp:BoundField DataField="AuthorName" HeaderText="AuthorName"
SortExpression="AuthorName" />
<asp:BoundField DataField="AuthorlName" HeaderText="AuthorlName"
SortExpression="AuthorlName" />
<asp:BoundField DataField="ItemType" HeaderText="ItemType"
SortExpression="ItemType" />
<asp:BoundField DataField="PublishYear" HeaderText="PublishYear"
SortExpression="PublishYear" />
<asp:BoundField DataField="numOfCopies" HeaderText="Number of Copies"
SortExpression="numOfCopies" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Items] WHERE ([Title] LIKE '%' + #Title + '%')">
<SelectParameters>
<asp:FormParameter FormField="tSearchBox" Name="Title" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<asp:Label ID="Label1" runat="server" Text="Type ISBN to loan:"></asp:Label>
And here is the .cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Pages_SearchResults : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Users\\SUUSER\\Documents\\Visual Studio 2010\\Projects\\Library\\LibWebSite\\App_Data\\LibDatabase.mdf;Integrated Security=True;User Instance=True";
Int32 verify;
string title = GridView1.HeaderRow.Cells[0].Text, isbn = GridView1.HeaderRow.Cells[1].Text, name = GridView1.HeaderRow.Cells[2].Text, lname = GridView1.HeaderRow.Cells[3].Text, type = GridView1.HeaderRow.Cells[4].Text, year = GridView1.HeaderRow.Cells[5].Text;
}
protected void bLoanButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Users\\SUUSER\\Documents\\Visual Studio 2010\\Projects\\Library\\LibWebSite\\App_Data\\LibDatabase.mdf;Integrated Security=True;User Instance=True";
string user = "select CurrentID from CurrentUser";
SqlCommand cmd1 = new SqlCommand(user, con);
con.Open();
string get = cmd1.ExecuteScalar().ToString();
string query1 = "insert into LoanTable(StudId,ISBN,onBorrow) values ("
+ "'" + get + "'" + "," + "'" + tLoanBox.Text + "'" + ","
+ "'" + "1" + "'" + ")";
string numQuery = "select numOfCopies from Items where ISBN='" + tLoanBox.Text + "'";
SqlCommand cmdnumQuery = new SqlCommand(numQuery, con);
SqlCommand cmd2 = new SqlCommand(query1, con);
int result;
int num=Convert.ToInt32(cmdnumQuery.ExecuteScalar());
result = cmd2.ExecuteNonQuery();
if (num > 0)
{
if (result > 0)
Response.Redirect("LoanSuccesfull.aspx");
}
else
notAvailable.Visible = true;
con.Close();
}
}
And here is the code for loan button:
protected void bLoanButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Users\\SUUSER\\Documents\\Visual Studio 2010\\Projects\\Library\\LibWebSite\\App_Data\\LibDatabase.mdf;Integrated Security=True;User Instance=True";
string user = "select CurrentID from CurrentUser";
SqlCommand cmd1 = new SqlCommand(user, con);
con.Open();
string get = cmd1.ExecuteScalar().ToString();
string query1 = "insert into LoanTable(StudId,ISBN,onBorrow) values ("
+ "'" + get + "'" + "," + "'" + tLoanBox.Text + "'" + ","
+ "'" + "1" + "'" + ")";
SqlCommand cmd2 = new SqlCommand(query1, con);
int result;
result = cmd2.ExecuteNonQuery();
if (result > 0)
{
loanSuccesful.Visible = true;
Response.Redirect("LoanSuccesfull.aspx");
}
con.Close();
}
I appreciate any help. Thanks
All you have to do is In your bLoanButton_Click , add a line to rebind the Grid to the SqlDataSource :
protected void bLoanButton_Click(object sender, EventArgs e)
{
//your same code
........
GridView1.DataBind();
}
regards
I was totally lost on why my Gridview.Databind() would not refresh.
My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:
gvServerConfiguration.Databind()
uppServerConfiguration.Update()
uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.
Hope this helps someone.
Before data bind change gridview databinding method, assign GridView.EditIndex to -1. It solved the same issue for me :
gvTypes.EditIndex = -1;
gvTypes.DataBind();
gvTypes is my GridView ID.
Adding the GridView1.DataBind() to the button click event did not work for me. However, adding it to the SqlDataSource1_Updated event did though.
Protected Sub SqlDataSource1_Updated(sender As Object, e As SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Updated
GridView1.DataBind()
End Sub

Search GridView

I have a guestbook at the moment displaying "comment", "comment_time", "user". I want to add a search box below and then search the gridview by "user" and then bind the data to a new grid view below. I am under strict instructions to have all data interactions passed via a web service.
I have a Web Method at the moment to get all the comments:
[WebMethod]
public DataSet SearchDatabase(string query)
{
DataSet ds = new DataSet();
string database = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/dvd_forum.accdb;Persist Security Info=True";
string queryStr = "SELECT * FROM Comments WHERE User LIKE '%query%'";
OleDbConnection myConn = new OleDbConnection(database);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(queryStr, myConn);
myConn.Open();
myDataAdapter.Fill(ds, "Comments");
myConn.Close();
return ds;
}
Here's the front code:
<asp:Label ID="Label3" runat="server" Text="Search"></asp:Label><asp:TextBox ID="TextBoxSearch"
runat="server"></asp:TextBox><asp:Button ID="ButtonSearch"
runat="server" Text="Search" onclick="ButtonSearch_Click" />
<asp:GridView ID="GridView2" runat="server">
The code behind:
protected void ButtonSearch_Click(object sender, EventArgs e)
{
string query = TextBoxSearch.Text;
localhost.Service1 myws = new localhost.Service1();
ds = myws.SearchDatabase(query);
GridView2.DataSource = ds;
GridView2.DataBind();
}
It just doesn't do anything at all, page refreshes with no new GridView or any other action.
On another side note:
I have another input on the same page with a required field validator that doesn't let me search unless I fill the input with some text. How can I resolve this?
Thanks.
string queryStr = "SELECT * FROM Comments WHERE User LIKE '%"+query+"%'";

Pls modify this code for retrieving the image from sqldatabase

I am still suffering from retrieving an image from a SQL database. This is my final solution for inserting and retrieving an image from database. Here is all my code:
GUI part:
<div>
<asp:Label ID="lblImage" runat="server" Text="Image"></asp:Label>
<asp:FileUpload ID="imageUpload" runat="server" />
<br />
<asp:Label ID="lblFilename" runat="server" Text="Filename"></asp:Label>
<asp:TextBox ID="txtFilename" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="BtnSave" runat="server" Text="SAVE" onclick="BtnSave_Click" />
<br />
<br />
<br />
<asp:Image ID="Image1" runat="server" />
</div>
And under the Button click event i have written the following code:
protected void BtnSave_Click(object sender, EventArgs e)
{
string uploadFileName = string.Empty;
byte[] imageBytes = null;
if (imageUpload != null && imageUpload.HasFile)
{
uploadFileName = imageUpload.FileName;
imageBytes = imageUpload.FileBytes;
}
string str = ConfigurationManager.ConnectionStrings["ImageConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand("INSERT INTO REPORT_TABLE (IMAGEFIELD,IMAGENAME) VALUES (#image,#filename)", con);
com.Parameters.Add("#image", SqlDbType.Image, imageBytes.Length).Value = imageBytes;
com.Parameters.Add("#filename", SqlDbType.VarChar, 50).Value = uploadFileName;
con.Open();
com.ExecuteNonQuery();
con.Close();
SqlConnection conn = new SqlConnection(str);
string sql = "SELECT * FROM [REPORT_TABLE]";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataRow dr = ds.Tables[0].Rows[0];
Byte[] b = (Byte[])dr["IMAGEFIELD"];
MemoryStream ms = new MemoryStream(b);
**this.pictureBox1.Image = Image.FromStream(ms)**; //(This code is for a Windows application but I want to retrieve an image from a web application) so what should be written instead of the highlighted code? In imagecontrol, image id is Image1.
}
you can server image like this:
.....
Image img= Image.FromStream(ms);
Response.Clear();
Response.ContentType = "image/jpeg";
img.Save(Response.OutputStream, ImageFormat.Jpeg);
}
but this will not put image in the <asp:Image ID="Image1" runat="server" /> because it needs image url not the image object :(
what you can do is setup a separate page to serve image and pass it image id or other unique identifier associated with image to show it in the <asp:Image ID="Image1" runat="server" />. simply add new page to your solution say ImageServer.aspx and in page_load write following:
protected void Page_Load(object sender, EventArgs e)
{
if(Request.QueryString.HasValues())
{
var id=Request.QueryString["id"];
if(!string.IsEmptyOrNull(id))
{
SqlConnection conn = new SqlConnection(str);
//CHANGE SELECT TO GET ONLY IMAGE WITH PASSED ID
string sql = "SELECT * FROM [REPORT_TABLE]";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataRow dr = ds.Tables[0].Rows[0];
Byte[] b = (Byte[])dr["IMAGEFIELD"];
MemoryStream ms = new MemoryStream(b);
Response.Clear();
Response.ContentType = "image/jpeg";
var img=system.Drawing.Image.FromStream(ms);
img.Save((Response.OutputStream, ImageFormat.Jpeg);
Response.Flush();
return;
}
//HERE YOU MAY RETURN DEFAULT OR ERROR IMAGE
}
}
Now change you button click in upload page as follows:
protected void BtnSave_Click(object sender, EventArgs e)
{
....
//SAVE IMAGE TO DB AND GET IMAGE ID (TO IDENTIFY THIS IMAGE)
image.ImageUrl = "YOUR_SERVER\ImageServer.aspx?id=" + IMAGE_ID;
}

Resources