I had Image control and I added code to display images But there is not any image displayed
ASPX:
<body>
<form id="form1" runat="server">
<div dir='<%= sDirection %>'>
<div id="ContentImage" runat="server">
<asp:Image ID="Image2" runat="server" />
</div>
</div>
</form>
</body>
C#:
using (System.Data.SqlClient.SqlConnection con = Connection.GetConnection())
{
string Sql = "Select Image From AboutUsData Where Id=#Id";
System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand(Sql, con);
com.CommandType = System.Data.CommandType.Text;
com.Parameters.Add(Parameter.NewInt("#Id", Request.QueryString["Id"].ToString()));
System.Data.SqlClient.SqlDataReader dr = com.ExecuteReader();
if (dr.Read() && dr != null)
{
Image2.ImageUrl = dr["Image"].ToString();
}
}
Is there any exception thrown when running DB command? Does dr["Image"] contain some value? What about CSS, ContentImage maybe hiding div container?
Looking at your code it seems you're setting the ImageUrl property for Image1 instead of Image2.
Also, you have to make sure that the ImageUrl path returned actually maps to an image on the server (wether relative or absolute). To put an example, if your code renders this image:
<img src="images/photo.gif" alt="my photo2" />
but there is no image in images/photo.gif, because its actually located in ../images/photo.gif (the images directory sits elsewhere) then no image will be displayed by the browser.
Related
I'm having a project to create a website that connects my database to perform different functionalities. When I create the web form and connects it with the database, and when i click the button it's supposed that all the products will appear but it doesn't happen.
This is the SQL procedure:
CREATE PROC reviewOrders
AS
BEGIN
SELECT *
FROM Orders
END
And this is the c# code
protected void reviewOrders(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("reviewOrders", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
and the HTML code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ReviewOrders.aspx.cs"
Inherits="GUCommerce.ReviewOrders" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="viewOrders" runat="server" OnClick ="reviewOrders" Height="45px"
Text="view orders" Width="148px" />
</div>
<p style="height: 121px">
</p>
<asp:Panel ID="x" Visible ="false" runat="server" Height="338px">
<asp:Table ID="orders" CellPadding ="4" runat="server" Height="67px" Width="316px">
</asp:Table>
</asp:Panel>
</form>
</body>
</html>
Can one please tell me what is missing?
Thanks is advance!
I would recommend using ASP Gridview instead of ASP Table. Gridviews (<asp:GridView>) are used to present data in tables. They actually get rendered as html tables. Here is how to build one using your code:
<asp:Panel ID="x" Visible="false" runat="server" Height="338px">
<%--<asp:Table ID="orders" CellPadding="4" runat="server" Height="67px" Width="316px"></asp:Table>--%>
<asp:GridView ID="gvOrders" CellPadding="4" runat="server" Height="67px" Width="316px"></asp:GridView>
</asp:Panel>
Now, in the code-behind there are a couple changes. A DataTable can be used to store the results of your query and then you can bind a DataTable to a GridView. To do this, you need a SqlDataAdapter which is shown below.
protected void reviewOrders(object sender, EventArgs e)
{
// data table variable outside of sql block
// you could also move the sql code to another method that returns a datatable
DataTable dt = null;
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
using (SqlConnection conn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("reviewOrders", conn);
cmd.CommandType = CommandType.StoredProcedure;
using (cmd)
{
conn.Open();
// Use SQL Data Adapter instead of Execute Non Query
using (SqlDataAdapter _Adapter = new SqlDataAdapter(cmd))
{
// Fill DataTable with results of query
dt = new DataTable();
_Adapter.Fill(dt);
}
}
}
//
gvOrders.DataSource = dt;
gvOrders.DataBind();
}
Note: I use using(SqlConnection) and using(cmd) to handle closing the connection and command for me. Give this a shot.
this is the place where i want to display the images
`<asp:Repeater ID="rptr" runat="server">
<ItemTemplate>
<asp:Image ID="img1" style="height:120px; width:120px" runat="server" />
</ItemTemplate>
</asp:Repeater>
`
this is the code i have used to retrieve images
string query = "select Image from tblImage where UserName='" + uname + "'";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(query, scon);
da.Fill(ds);
rptr.DataSource = ds;
rptr.DataBind();
now i want to set imageurl for the image control present within repeater control but the problem is that my image is present in binary form so i cant set the imageurl as ImageImageUrl='<%#Eval("Image") %>'("Image" is Column Name of the table where Image is stored in binary form). How can i convert the image into string format and set that into ImageUrl
HTML img element like so:
<asp:Image ID="image" style="height:120px; width:120px" runat="server"/>
And in code behind do this:
image.src = "data:image/png;base64," + Convert.ToBase64String(imageBytes);
Where imageBytes is a byte[] which you retrieve from database.
You are done. The image will be displayed.
I have multiple images which i want to display. the image count varies on input. I am able to see the broken images on the screen. In console the ERR_INVALID_URL is displayed. Please let me know where i am wrong.
Below is my aspx code
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Image ID="Image3" runat="server"
ImageUrl="data:image/jpg;base64,<%# ((view_data)Container.DataItem).image%>" />
</ItemTemplate>
</asp:Repeater>
cs code
foreach (DataRow row in dt.Rows)
{
Byte[] bytes = (Byte[])row["image"];
viewDataList.Add(new view_data { image = Convert.ToBase64String(bytes)});
}
Repeater1.DataSource = viewDataList;
Repeater1.DataBind();
I am fetching the images from database.Is this the correct way to do this.. Kindly suggest
Update..
I have changed the image tag to the below. Now there are 4 images that need to be displayed out of which i am able to see 1 image and the rest 3 are broken.. Kindly suggest
<img src="data:image/jpg;base64,<%# ((view_data)Container.DataItem).image%>" />
Try in this way with your requirements. Let me know, if you have any issues once you completed with below methods.
Note: I tried with separate column name as Image ID.If you have it in your database it will be of more useful to proceed this. Otherwise, you pass the Image directly to the repeater and pass the same to the ImageHandler.ashx
HTML Page:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Image ID="Image3" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("ImageID") %>' Height="150px" Width="150px"/>
</ItemTemplate>
CS Code:
On your click event:
SqlConnection connection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("SELECT imagename,ImageID from [Image]",connection);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
Repeater1.DataSource = dt;
Repeater1.DataBind();
ImageHandler.ashx
After Completion of above code we need to add HTTPHandler file to our project to retrieve images from database because we save our images in binary format getting the binary format of data from database it’s easy but displaying is very difficult that’s why we will use HTTPHandler to solve this problem.
Here HTTPHandler is a simple class that allows you to process a request and return a response to the browser. Simply we can say that a Handler is responsible for fulfilling requests from the browser. It can handle only one request at a time, which in turn gives high performance.
Right Click on your project add new HTTPHandler.ashx file and give name as ImageHandler.ashx and write the following code in pagerequest method like this
string strcon =ConfigurationManager.AppSettings["ConnectionString"].ToString();
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["ImID"];
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand command = new SqlCommand("select Image from Image where ImageID="+ imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
Here don’t forgot to set the connection string in web.config file here I am getting database connection from web.config file for that reason you need to set the connectionstring in web.config file like this
<connectionStrings>
<add name="dbconnection" connectionString="DataSource=Yourservername;Integrated Security=true;InitialCatalog=Your databasename"/>
</connectionStrings>
Source: Retrieve Image from database
Changing the image tag to the below worked for me..
<img src="data:image/jpg;base64,<%# ((view_data)Container.DataItem).image%>" />
Thanks for your response
There is no need to foreach to bind data in repeater you can directly specify DataTable to Your repeater control
DataTable dt=new DataTable();
dt=cmd.ExecuteNonQuery();
Repeater1.DataSource = dt;
Repeater1.DataBind();
you can place this line
<asp:Image ID="Image3" runat="server"
ImageUrl='<%#Bind("image")%>' />
instead of
<asp:Image ID="Image3" runat="server"
ImageUrl="data:image/jpg;base64,<%# ((view_data)Container.DataItem).image%>" />
I have a ListView filled with data from a DataSet loaded out of a MySql database. The ListView shows a list of text modules to create a word- file later. Here is the ListView definition:
<asp:ListView ID="addTextModuleList" runat="server" OnItemCommand="addTextModuleList_OnItemCommand" DataKeyNames="ID" >
<ItemTemplate>
<asp:LinkButton ID="addTextModuleButton" runat="server" CssClass="insertTextModuleButtonFade" CommandName="insertTextModule"></asp:LinkButton>
<div id="listViewId" runat="server" style="float:left; width:24px; height:16px; margin:2px 15px 5px 0px; text-align:right;"><%# Eval("ID") %></div>
<div style="float:left; width:200px; height:25px; margin:2px 10px 5px 0px; text-align:left; font-weight:bold;"><%# Eval("shortName") %>:</div>
<div style="float:left; width:700px; margin:5px;"><%# Eval("fullName") %></div>
<div class="clear"></div>
</ItemTemplate>
</asp:ListView>
I want to add textModules to the confirmation by clicking on an icon. And that's my problem. The icon has to be shown in different colors, depending on if the text module is already added or not. The icon is loaded as an asp:Linkbutton and I have a CSS class for the icon shown in green and another CSS class for the same icon in faded grey.
I can change the CssClass of the icon by clicking it but I do not know how to change the CssClass of the icon while loading the Page or the ListView. Any ideas?
Here is my codebehind for the DataSet:
protected void executeTemplateSelection()
{
// connect to database
MySqlConnection con = new MySqlConnection();
con.ConnectionString = Helper.CONNECTION_STRING;
MySqlCommand cmd = null;
// load customer textModules
con.Open();
cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM textmodule WHERE ID IN " + Session["loadTextModuleTemplates"].ToString();
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
addTextModuleList.DataSource = ds;
addTextModuleList.DataBind();
con.Close();
cmd = new MySqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM linktextmodule WHERE confirmationId = " + Session["currentConfirmationId"].ToString();
MySqlDataReader mdr = cmd.ExecuteReader();
ds.Tables[0].Columns.Add("alreadyAdded");
while (mdr.Read())
{
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
if (mdr["textModule"].Equals(ds.Tables[0].Rows[i]["ID"]))
{
ds.Tables[0].Rows[i]["alreadyAdded"] = "yes";
}
}
}
}
You can implement the ListView.ItemDataBound event (see http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemdatabound%28v=vs.100%29.aspx), which would allow you to change properties on the controls for each item as it's bound. I have used this approach before.
You could also try using the data binding syntax ( <%# %> ) directly in the CssClass attribute, though I'm not certain if that works inside the CssClass attribute like it does inside some other attributes. You're already doing that inside the div, but see for example http://support.microsoft.com/kb/307860 where they give an example inside an attribute.
Im trying to display name, description and a picture from my database with a repeater.
The Name and Description works as they should but the images won't show up. The images is located in a folder in my project and I'm trying to access them with a string that i have stored in the database "path" column.
oh, but if I look at the source code of the browser the src="" looks good, and i can even look at the pic in the browser if i paste the src to it..
Heres my code:
<head runat="server">
<title></title>
<style type="text/css">
.bilder {width:300;
height:200;
margin: 10px;
border: 1px solid black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater runat="server" ID="minRepeater">
<ItemTemplate>
<div class="wrapper">
<h1><%# DataBinder.Eval(Container.DataItem, "Name") %></h1>
<span id="desc"><%# DataBinder.Eval(Container.DataItem, "Description") %></span><br />
<img src="<%# DataBinder.Eval(Container.DataItem, "Path") %>" alt="test" class="bilder" />
<asp:Image ID="Image1" CssClass="bilder" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "Path")%>' runat="server" />
</div>
</ItemTemplate>
</asp:Repeater>
</div>
and codebehind:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = connectionstring;
SqlCommand com = new SqlCommand();
com.CommandText = "SELECT * FROM Pictures";
com.Connection = con;
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = com;
DataTable dt = new DataTable();
ad.Fill(dt);
Response.Write(dt.Rows.Count);
minRepeater.DataSource = dt;
minRepeater.DataBind();
}
(yes i know that my code isn't safe. at all.)
here's how it looks in a browser:
any ideas? :)
You may run it in Firebug or Chrome and see if the images are not found (404) and theirs path.
The error you're getting Not allowed to load local resource sounds like you are trying to load using a path on your local system. Trying using Server.MapPath with a relative path to the file, for example:
Server.MapPath("~/images/my-image.jpg");
Is your path like C:\\Images\etc...? If you are getting "Not allowed to load local resource", you should try your paths with relative paths.. if you dont have them in the WebSite you should make a copy of the image to the site and render that path. You are facing security problems.