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>
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.
I have a div in which user insert SQL query and I want to access this query in codebehind and pass to sqlcmd and execute query and show result to user but I'm unable to do this. How can I do this?
Here is my aspx code:
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<form id="form1" runat="server">
<div id="editor" contenteditable="true"></div>
<br />
<asp:Button runat="server" OnClick="load" Text="Submit" />
<asp:label ID="TextBox1" ForeColor="White" runat="server"></asp:label>
</form>
</asp:Content>
my aspx.cs (codebehind) is :
public void load(object sender, EventArgs e)
{
HtmlGenericControl footer = (HtmlGenericControl)FindControl("editor");
String cmd = footer.InnerHtml.ToString();
TextBox1.Text = cmd;
}
I'm getting this error:
Add runat="server" to your DIV tag and it should resolve your issue.
<div id="editor" contenteditable="true" runat="server"></div>
Add runat="server" in div like this:-
<div id="editor" contenteditable="true" runat="server">Lorem Ipsum</div>
and use this code
protected void Page_Load(object sender, EventArgs e)
{
ContentPlaceHolder mainContent = (ContentPlaceHolder)this.Master.FindControl("body");
HtmlGenericControl footer = (HtmlGenericControl)mainContent.FindControl("editor");
String cmd = footer.InnerHtml.ToString();
TextBox1.Text = cmd;
}
where body is ContentPlaceHolderID you can find this on your content page
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
Hope this will help you
I currently have a parent repeater and two child repeaters on my page. I am wanting to dynamically pull data from our database and display them within the repeaters. I followed the Microsoft guide and a few SO questions on how to do this, and this is what I have arrived at:
<!-- start parent repeater -->
<asp:repeater id="parentRepeater" runat="server">
<itemtemplate>
<li><div id="et_<%# DataBinder.Eval(Container.DataItem,"EquipmentTypeName") %>"><%# DataBinder.Eval(Container.DataItem,"EquipmentTypeName") %><label><input type="checkbox"></label></div><ul runat="server">
<!-- start child repeater1 -->
<asp:repeater id="Repeater1" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation") %>' runat="server">
<itemtemplate>
<li><div id="et_<%# DataBinder.Eval(Container.DataItem, "[\"MakeID\"]")%>"><%# DataBinder.Eval(Container.DataItem, "[\"MakeID\"]")%><label><input type="checkbox"></label></div><ul runat="server">
<!-- start child repeater2 -->
<asp:repeater id="childRepeater2" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation2") %>' runat="server">
<itemtemplate>
<li><div id="et_<%# DataBinder.Eval(Container.DataItem, "[\"YearID\"]")%>"><%# DataBinder.Eval(Container.DataItem, "[\"YearID\"]")%><label><input type="checkbox"></label></div><ul runat="server">
</ul></li></itemtemplate>
</asp:repeater>
<!-- end child repeater2 -->
</ul></li></itemtemplate>
</asp:repeater>
<!-- end child repeater1 -->
</ul></li></itemtemplate>
</asp:repeater>
<!-- end parent repeater -->
And the code behind is as follows:
protected void Page_Load(object sender, EventArgs e)
{
//Create the connection and DataAdapter for the Authors table.
string Connection = WebConfigurationManager.ConnectionStrings["md_dbConnectionString"].ConnectionString;
SqlConnection cnn = new SqlConnection(Connection);
SqlDataAdapter cmd1 = new SqlDataAdapter("select * from EquipmentType", cnn);
//Create and fill the DataSet.
DataSet ds = new DataSet();
cmd1.Fill(ds, "EquipmentType");
SqlDataAdapter cmd2 = new SqlDataAdapter("select * from Make", cnn);
cmd2.Fill(ds, "Make");
//Create a second DataAdapter for the Titles table.
SqlDataAdapter cmd3 = new SqlDataAdapter("select distinct MakeID, TypeID, YearID from Parts", cnn);
cmd3.Fill(ds, "Parts");
//Create the relation bewtween the Authors and Titles tables.
ds.Relations.Add("myrelation",
ds.Tables["EquipmentType"].Columns["EquipmentTypeID"],
ds.Tables["Parts"].Columns["TypeID"]);
ds.Relations.Add("myrelation2",
ds.Tables["Make"].Columns["MakeID"],
ds.Tables["Parts"].Columns["MakeID"]);
//Bind the Authors table to the parent Repeater control, and call DataBind.
parentRepeater.DataSource = ds;
Page.DataBind();
//Close the connection.
cnn.Close();
}
If I load the page with only one child repeater, everything works fine, I get the correct data displaying, but when I add the second child repeater in, I get the following error message: Unable to cast object of type 'System.Data.DataRow' to type 'System.Data.DataRowView'. This fires on thedatasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation2") %>'` ASP line.
The tables that I am trying to pull from are structured this way:
EquipmentType
EquipmentTypeID | EquipmentTypeName
Make
MakeID | MakeName
Year
YearID
Parts
PartID | MakeID | YearID | TypeID
Each table references the Parts table.
More or less what I want the repeater to do is display all of the EquipmentTypes, then only display the make is we have a part for it in the database. Once the make is selected, then only display the year that we have parts for that make and equipmenttype in the database.
Did you try to cast it to DataRow:
<%# ((DataRow)Container.DataItem).GetChildRows("myrelation2") %>
For anyone else experiencing this issue. It could be that there is a missing tag at the top of the page. <%# Import Namespace="System.Data" %>
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.
Here is the code behind:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
DetailsView1.Visible = true;
string csName = "showDetails";
StringBuilder sb = new StringBuilder();
sb.Append("document.getElementById('div_detailsView').style.display = 'block';");
sb.Append("document.getElementById('overlay').style.display = 'block';");
if (!ClientScript.IsClientScriptBlockRegistered(csName))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), csName, sb.ToString(), true);
}
Response.Write(GridView1.SelectedIndex + "<br>");
}
Here is the structure of my aspx page
<%# Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Summary.aspx.cs" Inherits="Summary" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server"></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<div>
<!-- Grid View Control placed here -->
</div>
<div id="div_detailsView">
<!-- Details View Control placed here -->
</div>
<div id="overlay"></div>
</asp:Content>
My intention is to create Lightbox/Graybox kinda effect where we have the DetailsView control placed in the central box of screen while the background grayed out. I am trying the css approach here and using js code should be very minimal.
But for some reason, I keep getting document.getElementByID("div_detailsView") is null error. I don't know why I can't execute the client script in this case. Could anyone give me a hand please? Thanks.
It is possible that script is invoked before page is fully loaded. Try using RegisterStartupScript instead.