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

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>");
}
}

Related

How to save and retrieve image from database in ASP.NET

I want to show image in image control on page load. I'm using the following code. My problem is that the image is saved in the database as binary data, but I can't retrieve the image in the image control
public partial class TeacherProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
profilepic();
}
protected void upload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
HttpPostedFile file = FileUpload1.PostedFile;
Byte[] imgbyte = new Byte[file.ContentLength];
file.InputStream.Read(imgbyte, 0, file.ContentLength);
SqlCommand cmd = new SqlCommand("Update Registration set Photo = '" + imgbyte + "' where id ='" + idd.Text + "' ", con);
//cmd.Parameters.AddWithValue("#userid", 222); //image id
//cmd.Parameters.AddWithValue("#pic", imgbyte);
//try
//{
con.Close();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "Image Uploaded";
con.Close();
//}
//catch
//{
// Label1.Text = "Try Again";
//}
}
}
public void profilepic()
{
SqlCommand cmd2 = new SqlCommand("select Photo from Registration where Username = '" + username1.Text + "'", con);
//cmd2.Parameters.AddWithValue("#userid", username1.Text);
con.Open();
SqlDataReader dr = cmd2.ExecuteReader();
if (dr.Read())
{
byte[] bytes = (byte[])dr["Photo"];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image1.ImageUrl = "data:image/png;base64," + base64String;
cmd2.ExecuteNonQuery();
con.Close();
}
else
{
}
}
}
Can anybody help me please?
Thanks in advance...
my code for file upload
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="fileUpload.aspx.cs" Inherits="fetchImage.fileUpload" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
margin-left: 0px;
}
.auto-style2 {
margin-left: 6px;
margin-top: 0px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<div>
<asp:TextBox ID="TextBox1" runat="server" CssClass="auto- style1"></asp:TextBox>
<asp:Button ID="Button1" runat="server" CssClass="auto-style2" OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
file upload cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace fetchImage
{
public partial class fileUpload : System.Web.UI.Page
{
string path;
SqlConnection con = new SqlConnection("Data Source=DESKTOP- U0NOKBP\\SQLEXPRESS;Initial Catalog=Lnmi;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
FileUpload1.SaveAs(Request.PhysicalApplicationPath + "/Images/"+ FileUpload1.FileName.ToString());
path = "Images/"+FileUpload1.FileName.ToString();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Images values('"+path.ToString()+"','"+TextBox1.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
}
}
}
for showing the file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ShowImage.aspx.cs" Inherits="fetchImage.ShowImage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<table>
<tr>
<td>
<img src="<%#Eval("image_path") %>" height="100" width="100" />
<td><%#Eval("title") %></td>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
file show cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace fetchImage
{
public partial class ShowImage : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP- U0NOKBP\\SQLEXPRESS;Initial Catalog=Lnmi;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Images";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
con.Close();
}
}
}
please create a table before proceeding
create table Images(image_path varchar(MAX), title varchar(50));
and lastly add a folder Images in your project by right clicking at your project name

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

Reload GridView or Repeater on AjaxFileUpload UploadComplete Event in 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
}

ASP.NET C# - Dropdown list by using User Control

I am new to ASP.NET
Someone in this forum helped me how to get the dropdown list work wth user countrol and it is working.
In my user control file, VendorListControl.ascx, I have this code below. Please assume that the VendorListControl.ascx.cs works correctly, which is when I select a VendorName, it will fired "ddlVendor_SelectedIndexChanged" to refreshed the "ddlVendorBUList" dropdown list.
<%# Control Language="C#" AutoEventWireup="true" CodeFile="VendorListControl.ascx.cs" Inherits="MyNamespace.VendorListControl" %>
<asp:DropDownList runat="server" ID="ddlVendorList" onselectedindexchanged="ddlVendor_SelectedIndexChanged" AutoPostBack="True" />
<asp:DropDownList runat="server" ID="ddlVendorBUList" AutoPostBack="True" />
<asp:Label runat="server" ID="lblMessage" />
My VendorListControl.ascx.cs code:
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace MyNamespace
{
public partial class VendorListControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillVendors();
}
}
protected void ddlVendor_SelectedIndexChanged(object sender, EventArgs e)
{
int VendorID = Convert.ToInt32(ddlVendorList.SelectedValue.ToString());
FillVendorBU(VendorID);
}
private void FillVendors()
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorID, VendorName FROM MDF_Vendor";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd; ;
conn.Open();
dAdapter.Fill(objDs);
conn.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
this.ddlVendorList.DataSource = objDs.Tables[0];
this.ddlVendorList.DataTextField = "VendorName";
this.ddlVendorList.DataValueField = "VendorID";
this.ddlVendorList.DataBind();
this.ddlVendorList.Items.Insert(0, "-- Select --");
}
else
{
this.lblMessage.Text = "No Vendor Found";
}
}
private void FillVendorBU(int VendorID)
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorBUID, VendorBUName FROM dbo.MDF_VendorBU WHERE VendorID = #VendorID";
cmd.Parameters.AddWithValue("#VendorID", VendorID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddlVendorBUList.DataSource = objDs.Tables[0];
ddlVendorBUList.DataTextField = "VendorBUName";
ddlVendorBUList.DataValueField = "VendorBUID";
ddlVendorBUList.DataBind();
ddlVendorBUList.Items.Insert(0, "--Select--");
}
else
{
lblMessage.Text = "No states found";
}
}
}
}
Next, in my CreateNewRecord.aspx page, I have this code to include both dropdown list from user control. And I can see the dropdown lists works properly.
<%# Register TagPrefix="uc" TagName="VendorListControl" Src="Controls/VendorListControl.ascx" %>
// Some where in the form
<tr>
<td class="right" width="20%">Vendor Name:</td>
<td>
<uc:VendorListControl runat="server" />
</td>
</tr>
The problem is related to the ID of those two dropdown lists. When I attemp to do the insert record, it seems not to detect the ID for "ddlVendorList" and "ddlVendorBUList" come from user control ascx page. Error " The name 'ddlVendorList' does not exist in the current context"
ExecuteInsert(ddlVendorList.SelectedItem.Text,
ddlVendorBUList.SelectedItem.Text,
MDFAmount.Text,
StartDate.Text,
EndDate.Text,
VendorQuarter.Text,
MDFName.Text,
MDFSummary.Text,
Status.SelectedItem.Text,
CreatedBy.Value
);
Response.Write("<b>Record was successfully added!</b>");
I know I am new to ASP.NET, so please help.
You can put two properties in your VendorListControl to get the ddlVendorList selectedItem text and the ddlVendorBUList selectedItem text.
In VendorListControl.ascx.cs :
public string GetDdlVendorListSelectedItemText
{
get { return this.ddlVendorList.text; }
}
public string GetDdlVendorBUListSelectedItemText
{
get { return this.ddlVendorBUList.text; }
}
Then from your page CreateNewRecord, you can access those properties. You just need to add an id to your control :
<%# Register TagPrefix="uc" TagName="VendorListControl" Src="Controls/VendorListControl.ascx" %>
// Some where in the form
<tr>
<td class="right" width="20%">Vendor Name:</td>
<td>
<uc:VendorListControl id="vendorListControl" runat="server" />
</td>
</tr>
And you can access your properties like this in CreateNewRecord.aspx.cs :
ExecuteInsert(this.vendorListControl.GetDdlVendorListSelectedItemText,
this.vendorListControl.GetDdlVendorBUListSelectedItemText,
MDFAmount.Text,
StartDate.Text,
EndDate.Text,
VendorQuarter.Text,
MDFName.Text,
MDFSummary.Text,
Status.SelectedItem.Text,
CreatedBy.Value
);
You define public property who return SelectedItem.Text in your UserControl.
User Control (Ascx)
public string YourValue
{
get
{
return ddlVendorList.SelectedItem.Text;
}
}
Page (Aspx)
You can use your public property : YourValue.
ExecuteInsert(YourValue,
....... );
Nota : if you wish set value, you define setter on your property
After your update add theses properties
public string YourDdlVendorListSelectedItemText
{
get
{
return this.ddlVendorList.text;
}
}
public string YourDdlVendorBUListSelectedItemText
{
get
{
return this.ddlVendorBUList.text;
}
}

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