Images not displaying, asp:repeater - c#

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.

Related

How link/bind textbox, dropdown list and SQL database together on C#?

Basically what the task is that you search someone's name in the textbox, click search, the users with that name will populate the dropdown list.
SQL Server: this is the query I am try to add to the search button on my page:
SELECT Users.Forename + ' ' + Users.Surname AS [Name], Users.ID
From Users
Order by [Name]
Aspx side:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Page1.aspx.cs" Inherits="SearchRecords.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p> Search User </p>
<p> Filter Users: <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<asp:Button ID="SearchButton1" runat="server" Text="Search" OnClick="BtnSearch_Click" />
<br />
<br />
Select a user:
<asp:DropDownList ID="DDLSelectUser1" runat="server"> </asp:DropDownList>
<asp:Label ID="lblUserCount" runat="server" Text=""></asp:Label>
<br />
<div class="DataGrid">
<asp:GridView ID="DataGrid1" runat="server" ShowHeaderWhenEmpty="false" EmptyDataText="No data found!">
</asp:GridView>
</div>
</p>
<p> Link to page 1 </p>
</div>
</form>
</body>
</html>
C# side: I've got this already (this is me attempting to fetch data from the Database and bind the list of names to the dropdown list):
private void LoadIntoDropdown()
{
using (SqlConnection connection = new SqlConnection("Data Source=DEV-WEB;Initial Catalog=Isabelle;Integrated Security=True"))
{
connection.Open();
string sqlQuery = "SELECT Users.Forename + ' ' + Users.Surname AS [Name], Users.ID From Users WHERE Forename like '%'+#Forename+'%'";
using (SqlCommand cmd = new SqlCommand(sqlQuery, connection))
{
cmd.Parameters.AddWithValue("Forename", TextBox1.Text);
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
DDLSelectUser1.DataTextField = "[Name]";
DDLSelectUser1.DataValueField = "Users.ID";
DDLSelectUser1.DataSource = dt;
DDLSelectUser1.DataBind();
}
}
connection.Close();
}
}
It's never working, this is what I get:
"DataBinding: 'System.Data.DataRowView' does not contain a property with the name '[Name]'."
And I don't understand why? I combined two columns from the database, the Forename and Surname columns, together and called it [Name], so it does exist.
I can't seem to find online the right answer to my question as they all are 'select from the dropdown list to fill the textbox' I want the other way around, if it's possible!
The alias [Name] in your query becomes just Name once the database returns the resultset to the client (in this case, your program). So, when you reference that column in your code, you should do it as Name instead of [Name]
DDLSelectUser1.DataTextField = "Name";
Square bracket names and aliases are used in SQL Server queries both to specify that you want the name/alias to be exactly as written (including "invalid" characters for names like spaces e.g. [First Name]) and to differentiate such names/aliases from keywords (althought using keywords as field names is not recommended).
You can find more information in this SO question and in this Microsoft Docs' question

the button is not doing its supposed function

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.

How do I Bind in ASP to a SQLDataSource?

I'm trying to wrap my head around databinding using a sqldatasource. Right now I have a sqldatasource, databound fields, and template fields that I bind using:
<%# Bind("ColumnName") %>. I understand databound fields, but when using the "Bind" command on a template field, how does it know the value to put there? Does it find the ID for the row and then use the sqldatasource to get the value?
Also, how would I go about doing the same thing as "Bind" in ASP, but in the C# code behind instead?
Check the following article:
ASP.NET data binding overview
Visual C# .NET
<%# Page language="c#" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
SqlConnection cnn = new
SqlConnection("server=(local);database=pubs;Integrated Security=SSPI");
SqlDataAdapter da = new SqlDataAdapter("select * from authors", cnn);
DataSet ds = new DataSet();
da.Fill(ds, "authors");
Repeater1.DataSource = ds.Tables["authors"];
Repeater1.DataBind();
}
</script>
<html>
<body>
<form id="WebForm2" method="post" runat="server">
<asp:Repeater id="Repeater1" runat="server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"au_id") %><br>
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>

Place text into a SQL Server 2005 database

I have a SQL database with 1 table with 3 columns.. documentID, documentTitle, documentBody.
I have an aspx page with 2 inputs... 1 for title 1 for body and 1 submit button.
How on earth do I just get the text inside the input fields to store in a new row in the database? I cannot find a simple... concrete answer and there is no way that it is that complicated.
<form id="form1" runat="server">
<div style="width: 800px; margin-top: 40px;">
<p style="text-align: left">
Title</p>
<p>
<input id="inputTitle" runat="server" type="text" style="width: 100%; padding: 6px;
font-size: large" /></p>
<p style="text-align: left">
Body</p>
<p>
<textarea id="inputBody" runat="server" style="width: 100%; height: 400px" cols="22"
rows="66"></textarea></p>
<p>
<input id="save" type="submit" onclick="submit_onclick" value="Save as the newest version" /><span> or
</span><a href>Cancel</a></p>
</div>
</form>
The simplest would be to use straight ADO.NET in the OnClick handler - but that leads to spaghetti code and intermingling of UI manipulation (setting and reading e.g. textboxes) and data access code - which is not a good approach.
Anywhere - here goes the simplest approach (again: not recommended for real use)
protected void submit_onclick(object sender, EventArgs e)
{
string sqlStmt = "INSERT INTO dbo.YourTable(documentTitle, documentBody) " +
"VALUES(#docTitle, #docBody)";
string connectionString = WebConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
using(SqlConnection conn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(sqlStmt, conn))
{
cmd.Parameters.Add("#docTitle", SqlDbType.VarChar, 100).Value = tbxTitle.Text.Trim();
cmd.Parameters.Add("#docBody", SqlDbType.VarChar, 100).Value = tbxBody.Text.Trim();
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
Of course - using an ORM might make things easier from a programming perspective (just "new up" a Document, set its .Title and .Body properties, and call .Save() on it - or something like that) - but these ORM's do have a certain learning curve, too.
Also: if you're looking at doing simple to medium-complexity stuff or if you're just getting into ASP.NET development - why not check out Microsoft WebMatrix? It contains a lot of helpers and "wrappers" that make dealing with typical tasks much easier - especially the database, for one!
See part 5 of the intro tutorial on database development.
Use ASP.NET server controls for your inputs, instead of an <input>.
<asp:Button runat="server" Text="Submit" id="sub" OnClick="SaveDetails" />
<asp:TextBox runat="server" id="txtBody" />
<asp:TextBox runat="server" id="txtTitle" />
Try something like this in your code-behind:
protected void SaveDetails(object sender, EventArgs e) {
using (var conn = new SqlConnection("Data Source=YourServerName;Initial Catalog=YourDatabaseName;Integrated Security=True;"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = #"INSERT INTO docs (documentTitle, documentBody)
VALUES (#title,#body);";
cmd.Parameters.AddWithValue("#title", txtTitle.Text.Trim());
cmd.Parameters.AddWithValue("#body", txtBody.Text.Trim());
cmd.ExecuteNonQuery();
}
}

Cannot display image

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.

Categories

Resources