I am building a website with ASP.NET Web Forms, and a SQL database.
On one particular page I have a number of houses with some informations.
There are 571 houses in total.
When I click on a particular house, I want to bring up a new page with more information about that house.
All the data is coming from a table in the database.
Is there a way of knowing which house has been selected, and display the data on the new aspx page for that house?
I know I could create many separate aspx pages for each house but there are 571 houses and there would have to be 571 aspx pages. That is far too much wasted code.
When I click on the house name I want only one aspx page but I want it to know that I have selected that house and display the information for that specific one. Like its accessing the database information for that house and displays it.
The main obstacle here is knowing what house has been selected. I know how to display information from a database.
Houses.aspx
When I click a house name I want to display a page like the one below.
HouseInfo.aspx
HouseInfo.aspx.cs
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand command = new SqlCommand("SELECT Id, Name, Townland, Near, Status, Built, Description, Families FROM Houses ORDER BY Name DESC", connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
lblId.Text = reader[0].ToString();
lblName.Text = reader[1].ToString();
lblTown.Text = reader[2].ToString();
lblNear.Text = reader[3].ToString();
lblStatus.Text = reader[4].ToString();
lblBuilt.Text = reader[5].ToString();
lblDesc.Text = reader[6].ToString();
lblFam.Text = reader[7].ToString();
}
}
}
}
}
This is how I am accessing the database to display some of the info on the HouseInfo page already.
HouseInfo.aspx
<b>ID:</b> <asp:Label ID="lblId" runat="server"></asp:Label>
<br /><b>Name of House:</b> <asp:Label ID="lblName" runat="server"></asp:Label>
<br /><b>Townland:</b> <asp:Label ID="lblTown" runat="server"></asp:Label>
<br /><b>Near:</b> <asp:Label ID="lblNear" runat="server"></asp:Label>
<br /><b>Status/Public Access:</b> <asp:Label ID="lblStatus" runat="server </asp:Label>
<br /><b>Date Built:</b> <asp:Label ID="lblBuilt" runat="server"></asp:Label>
<br /><b>Description:</b> <asp:Label ID="lblDesc" runat="server"></asp:Label>
<br /><b>Associated Families:</b> <asp:Label ID="lblFam" runat="server"></asp:Label>
Houses.aspx
<%# Page Title="Houses" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="Houses.aspx.cs" Inherits="Houses_of_Mayo.images.Houses" EnableEventValidation="false" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script>
$(function () { setCurrentTab('tab2'); });
</script>
<div class="box">
<div>
<div class="body">
<h1>Houses</h1>
<ul id="rooms">
<asp:Repeater ID="rptData" runat="server" >
<ItemTemplate>
<li>
<a href="HouseInfo.aspx">
<img src="x" alt="img" /></a>
<h2>
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label></h2>
<p>
<b>ID: </b>
<asp:Label runat="server" Text='<%# Eval("Id") %>'></asp:Label>
<br />
<b>Name of House: </b>
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<br />
<b>Townland: </b>
<asp:Label runat="server" Text='<%# Eval("Townland") %>'></asp:Label>
<br />
<b>Near: </b>
<asp:Label runat="server" Text='<%# Eval("Near") %>'></asp:Label>
<br />
<b>Status/Public Access: </b>
<asp:Label runat="server" Text='<%# Eval("Status") %>'></asp:Label>
<br />
<b>Date Built: </b>
<asp:Label runat="server" Text='<%# Eval("Built") %>'></asp:Label>
</p>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
<asp:Repeater ID="rptPager" runat="server">
<ItemTemplate>
<asp:LinkButton ID="lnkPage" runat="server" Text='<%#Eval("Text") %>' CommandArgument='<%# Eval("Value") %>'
style="padding:8px; margin:2px; background:#ac9e94; border:solid 1px #666; font:8pt; color:#594334; display: inline-block;"
CssClass='<%# Convert.ToBoolean(Eval("Enabled")) ? "page_enabled" : "page_disabled" %>'
OnClick="Page_Changed" OnClientClick='<%# !Convert.ToBoolean(Eval("Enabled")) ? "return false;" : "" %>'></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
</div>
</asp:Content>
Houses.aspx.cs
private int PageSize = 5;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.GetCustomersPageWise(1);
}
}
private void GetCustomersPageWise(int pageIndex)
{
string constring = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("GetHousesPageWise", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PageIndex", pageIndex);
cmd.Parameters.AddWithValue("#PageSize", PageSize);
cmd.Parameters.Add("#RecordCount", SqlDbType.Int, 4);
cmd.Parameters["#RecordCount"].Direction = ParameterDirection.Output;
con.Open();
IDataReader idr = cmd.ExecuteReader();
rptData.DataSource = idr;
rptData.DataBind();
idr.Close();
con.Close();
int recordCount = Convert.ToInt32(cmd.Parameters["#RecordCount"].Value);
this.PopulatePager(recordCount, pageIndex);
}
}
}
private void PopulatePager(int recordCount, int currentPage)
{
double dblPageCount = (double)((decimal)recordCount / Convert.ToDecimal(PageSize));
int pageCount = (int)Math.Ceiling(dblPageCount);
List<ListItem> pages = new List<ListItem>();
if (pageCount > 0)
{
for (int i = 1; i <= pageCount; i++)
{
pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
}
}
rptPager.DataSource = pages;
rptPager.DataBind();
}
protected void Page_Changed(object sender, EventArgs e)
{
int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
this.GetCustomersPageWise(pageIndex);
}
Map (HouseInfo.aspx)
HouseInfo.aspx
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script>
function initialize() {
var myLatlng = new google.maps.LatLng(53.613873, -9.668301);
var mapOptions = {
zoom: 17,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<h2 id="firstHeading" class="firstHeading">Aasleagh Lodge</h2>' +
'<div id="bodyContent">' +
'<b>ID:</b> A1' +
'</br><b>Name:</b> Aasleagh Lodge' +
'</br><b>Townland:</b> Srahatloe' +
'</br><b>Ref:</b> 1' +
'</br><b>Latitude:</b> 53.613873' +
'</br><b>Longitude:</b> -9.668301' +
'</div>' +
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var image = 'Images/icon56.png';
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Aasleagh Lodge',
icon: image
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
HouseInfo Table
[Id] CHAR (10) NOT NULL,
[Name] NVARCHAR (MAX) NULL,
[Townland] NVARCHAR (MAX) NULL,
[Ref] INT NULL,
[Lat] FLOAT (53) NULL,
[Lng] FLOAT (53) NULL,
CONSTRAINT [PK_HouseInfo] PRIMARY KEY CLUSTERED ([Id] ASC)
There are multiple ways to do that. Best (IMO) and easiest is to use query string to pass the ID (or primary key data) of the selected house to the next web-form and display data using that value.
in this code you are sending Id of house to other page.
<a href='<%# "HouseInfo.aspx?HouseId=" + Eval("Id").ToString() %>'>
<img src="x" alt="img" /></a>
and here you are getting that Id back
string HouseId = Request.Params["HouseId"].ToString();
also in here you are filtering your data to only get that houses information
"SELECT Id, Name, Townland, Near, Status, Built, Description, Families FROM Houses WHERE Id = '" + HouseId + "' ORDER BY Name DESC"
complete code ;
HouseInfo.aspx.cs
string HouseId = Request.Params["HouseId"].ToString();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand command = new SqlCommand("SELECT Id, Name, Townland, Near, Status, Built, Description, Families FROM Houses WHERE Id = '" + HouseId + "' ORDER BY Name DESC", connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
lblId.Text = reader[0].ToString();
lblName.Text = reader[1].ToString();
lblTown.Text = reader[2].ToString();
lblNear.Text = reader[3].ToString();
lblStatus.Text = reader[4].ToString();
lblBuilt.Text = reader[5].ToString();
lblDesc.Text = reader[6].ToString();
lblFam.Text = reader[7].ToString();
}
}
}
}
Houses.aspx
<ul id="rooms">
<asp:Repeater ID="rptData" runat="server" >
<ItemTemplate>
<li>
<a href='<%# "HouseInfo.aspx?HouseId=" + Eval("Id").ToString() %>'>
<img src="x" alt="img" /></a>
<h2>
<a href='<%# "HouseInfo.aspx?HouseId=" + Eval("Id").ToString() %>'><asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label></a></h2>
<p>
<b>ID: </b>
<asp:Label runat="server" Text='<%# Eval("Id") %>'></asp:Label>
<br />
<b>Name of House: </b>
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<br />
<b>Townland: </b>
<asp:Label runat="server" Text='<%# Eval("Townland") %>'></asp:Label>
<br />
<b>Near: </b>
<asp:Label runat="server" Text='<%# Eval("Near") %>'></asp:Label>
<br />
<b>Status/Public Access: </b>
<asp:Label runat="server" Text='<%# Eval("Status") %>'></asp:Label>
<br />
<b>Date Built: </b>
<asp:Label runat="server" Text='<%# Eval("Built") %>'></asp:Label>
</p>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
Related
I'm working in a Quiz Page where users can access and answers some questions. The problem I'm facing is when I want to display the possible answers of the questions. I want to display the options in a dropdownlist. I already have the questions in a datalist. Are there any ideas of how can I do it?
This is how it looks:
(In the arrows that I placed is where I want to display the options)
This is what users see
Here is what I have:
A FormQuiz.aspx:
<body style="background-color: #0f5298">
<form id="form1" runat="server">
<nav class="auto-style2" style="background-color: #d5f3fe">
<div class="auto-style3">
<a class="navbar-brand" href="#">
<img src="logo.png" alt="" class="auto-style1" />
Quiz
</a>
</div>
</nav>
<div class="card">
<asp:Label ID="LabelName" runat="server" Text="Seleccione un Quiz:" CssClass="lbl"></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="ddl" AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" >
<asp:ListItem Text="--- Seleccione ----" Value=" " />
</asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text="Instrucciones" CssClass="lbl"></asp:Label>
<asp:Label ID="LabelInstrucciones" runat="server" CssClass="I"></asp:Label>
<asp:Panel ID="Panel1" runat="server" CssClass="panelQ">
<asp:Label ID="Label2" runat="server" CssClass="section"></asp:Label>
<asp:DataList ID="DataList1" runat="server" CssClass="datalist">
<ItemTemplate>
<div style="margin-top: 2%">
<asp:Label ID="Label2" runat="server" Text='<%#Eval("Description") %>'></asp:Label>
</div>
<asp:DropDownList ID="DropDownOptions" runat="server" Width="200px" AppendDataBoundItems="true" AutoPostBack="true" DataSourceID="dsOptions" DataTextField="Options" DataValueField="Id">
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:DataList>
</asp:Panel>
</div>
</form>
</body>
This is how I get the questions in FormQuiz.aspx.cs:
public void SelectedSectionsTitlesQuestions(int id)
{
using (SqlConnection con = new SqlConnection(connectionstring))
{
con.Open();
string querySection = #"SELECT Mant.Sections.Name
FROM Mant.Quizzes
INNER JOIN Mant.Questions ON Mant.Quizzes.Id = Mant.Questions.Quiz_Id
INNER JOIN Mant.Sections ON Mant.Questions.Section_Id = Mant.Sections.Id
WHERE Mant.Quizzes.Id =" + id;
string queryQuestion = #"SELECT Mant.Questions.Description
FROM Mant.Quizzes
INNER JOIN Mant.Questions ON Mant.Quizzes.Id = Mant.Questions.Quiz_Id
WHERE Mant.Quizzes.Id =" + id;
SqlDataAdapter ad2 = new SqlDataAdapter(querySection, con);
DataSet ds2 = new DataSet();
ad2.Fill(ds2);
Label lblsection = (Label)FindControl("Label2");
lblsection.Text = ds2.Tables[0].Rows[0]["Name"].ToString(); ;
DataList datalistQuestions = (DataList)FindControl("DataList1");
SqlDataAdapter ad = new SqlDataAdapter(queryQuestion, con);
DataSet ds = new DataSet();
ad.Fill(ds);
datalistQuestions.DataSource = ds;
datalistQuestions.DataBind();
FillDropdown();
con.Close();
}
}
This is how I populate the dropdown with a SqlDataSource:
public void FillDropdown()
{
using (SqlConnection con = new SqlConnection(#"Server =hncrsap-sql01; Database=HEDS;User Id = sa; Password=Lear2005; MultipleActiveResultSets=true;"))
{
con.Open();
List<int> Types = new List<int>(TypeQuestionsId());
for(int x=0; x < Types.Count(); x++)
{
int TQuestions_Id = Types[x];
string queryTypeQuestion = #"SELECT TypeQuestions_Id
FROM Mant.Questions
WHERE Quiz_Id=" + id_Quiz +
"AND TypeQuestions_Id=" + TQuestions_Id;
SqlCommand SelectCommand = new SqlCommand(queryTypeQuestion, con);
SqlDataReader myreader;
myreader = SelectCommand.ExecuteReader();
while (myreader.Read())
{
string querySelectOptions = #"SELECT Options, Id
FROM Mant.AnswerOptions
WHERE TypeQuestions_Id=" + TQuestions_Id;
SqlDataSource dsOptions = new SqlDataSource();
dsOptions.ID = "dsOptions";
this.Page.Controls.Add(dsOptions);
dsOptions.ConnectionString = "Server =hncrsap-sql01; Database=HEDS;User Id = sa; Password=Lear2005; MultipleActiveResultSets=true;";
dsOptions.SelectCommand = querySelectOptions;
}
}
con.Close();
}
// return values;
}
But I got this error in the SelectedSectionsTitlesQuestions method
You can configure another SqlDataSource and bind it to your drop-down list.
<asp:DropDownList ID="ddlEmployees" runat="server" DataSourceID="SqlDataSource1"
DataTextField="EmployeeName" DataValueField="EmployeeID" AppendDataBoundItems="true">
<asp:ListItem Text="Please select" Value="" />
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DB_9EF896_weddingConnectionString %%>"
SelectCommand="SELECT (FirstName + ' ' + LastName) AS EmployeeName, EmployeeID FROM Employees">
</asp:SqlDataSource>
Result
I am trying to insert a comment using repeater Control
my code in html
<asp:Repeater ID="repConcerns" runat="server" OnItemCommand="post" >
<ItemTemplate >
<div class="row col-md-12">
<div class="col-sm-2" style="background-color:#808080">
<asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("Pathh") %>' width="90px" Height="90px" CssClass="img-circle" title='<%#Eval("Name") %>'/> <br/><asp:LinkButton ID="LinkButton1" runat="server" Text='<%#Eval("Name") %>' CssClass="btn btn-info btn-sm" CommandName="btnMessage" CommandArgument='<%#Eval("Username") %>'></asp:LinkButton><br/>
</div>
<div class="col-sm-10" style="background-color:#808080" >
<asp:Label ID="Label1" width="100%" style="padding:7px;" runat="server" Enabled="false" Text='<%#Eval("Title") %>'> </asp:Label>
<asp:TextBox ID="txtMessage" placeholder="Empty Post" width="100%" style="padding:7px;" runat="server" Text='<%#Eval("Detail") %>' TextMode="MultiLine" Enabled="false" Height="100px"> </asp:TextBox>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%#Eval("Sno") %>' />
<div class="bar"></div>
<asp:TextBox ID="txtcomment" runat="server" CssClass="form-control form-control-sm" placeholder="Comment / Write Openion Suggestion" TextMode="MultiLine" Height="40px"></asp:TextBox>
<asp:LinkButton ID="btn" runat="server" CssClass="btn btn-primary" CommandName="comment" CommandArgument='<%#Eval("Sno") %>' >Post</asp:LinkButton>
</div>
</div>
<div style="padding-bottom:10px;"></div>
<%--<br /> --%>
</ItemTemplate>
</asp:Repeater>
and C# code
protected void post(object source, RepeaterCommandEventArgs e)
{
if(e.CommandName== "comment")
{
a = e.CommandArgument.ToString();
SqlConnection con = new SqlConnection(strconn);
SqlCommand com = new SqlCommand();
com.CommandText = "insert into Comments(Sno,Comment,Username)values('" +a+ "','" + txtcomment.Text + "','" + username + "')";
con.Open();
}
}
I do not know how to insert into table "Comment".
I have made a "Page" in which their are wall posts. I have included an option for Comment. The comment button appears as it should with every post. But i do not know how to insert comment in table "Comment". i am trying to insert comment with corresponding "Sno" of Posts saved in HiddenField. But when i try to write Text Box id there "txtcomment.text" it gives me error. How do i insert.
I've made some amendments to you original code - note the comments:
protected void post(object source, RepeaterCommandEventArgs e)
{
if(e.CommandName== "comment")
{
//Find TextBox Control
TextBox txt = (TextBox)e.Item.FindControl("txtcomment");
var sno = e.CommandArgument.ToString();
SqlConnection con = new SqlConnection(strconn);
SqlCommand com = new SqlCommand();
com.CommandText = "INSERT INTO Comments(Sno,Comment,Username) VALUES (#SNO, #COMMENT, #USERNAME)";
com.Connection = con;
//Add Command Parameters
com.Parameters.AddWithValue("#SNO", sno);
com.Parameters.AddWithValue("#COMMENT", txt.Text);
com.Parameters.AddWithValue("#USERNAME", username);
con.Open();
//Execute Command
com.ExecuteNonQuery();
}
}
I have a DropDownList which contains the two columns one is CardCode and other is CardName and that is linked to a SQL database. It currently shows a list of CardCode + List of Cardname. I am trying to make it so that once a CardCode + CardName is selected from the two columns dropdownlist, multiple textboxes are automatically filled (such as CardNum, CntctPerson,ListNum etc). I am able to automatically fill the data from selecting only CardCode now I want to show the related row to the CardCode + CardName dropdown list, I do not know how to fill the other rows by selecting 2 column's dropdown list(CardCode + CardName) .How can i do this? Thanks In Advance
Here is my aspx.cs Code below
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 StackOver
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadOptions();
}
}
protected void LoadOptions()
{
DataTable CardCode = new DataTable();
SqlConnection connection = new SqlConnection("my connection string");
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT CardCode,CardName, Address, CntctPrsn FROM OCRD", connection);
adapter.Fill(CardCode);
DropDownList1.DataValueField = "CardCode";
DropDownList1.DataTextField = "CardCode";
DropDownList1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = DropDownList1.SelectedItem.Value;
SqlConnection connection = new SqlConnection("my connection string");
using (connection)
{
SqlCommand theCommand = new SqlCommand("SELECT CardCode, CardName, Address, CntctPrsn FROM OCRD WHERE CardCode = #CardCode", connection);
connection.Open();
theCommand.Parameters.AddWithValue("#CardCode", selected);
theCommand.CommandType = CommandType.Text;
SqlDataReader theReader = theCommand.ExecuteReader();
if (theReader.Read())
{
// Get the first row
// theReader.Read();
// Set the text box values
this.TextBox1.Text = theReader.GetString(0);
this.TextBox2.Text = theReader.GetString(1);
this.TextBox3.Text = theReader.GetString(2);
// this.TextBox3 = reader.IsDBNull(TextBox3Index) ? null : reader.GetInt32(TextBox3Index)
// GenreID = reader.IsDBNull(genreIDIndex) ? null : reader.GetInt32(genreIDIndex)
this.TextBox4.Text = theReader.GetString(3);
// TextBox5.Text = theReader.GetString(4);
// TextBox6.Text = theReader.GetString(5);
// TextBox7.Text = theReader.GetString(6);
}
connection.Close();
}
}
public object TextBox3Index { get; set; }
}
}
And also this is my .aspx code
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="StackOver._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource1" DataTextField="CardCode"
DataValueField="CardName"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:myconnectionstring %>"
SelectCommand="SELECT [CardCode] + '----' + [CardName] as CardCode, CardName,[Address], [CntctPrsn] FROM [OCRD]">
</asp:SqlDataSource>
</h2>
<br />
<br />
<p>
</p>
<p>
</p>
<p>
Business Partner Code :
<asp:TextBox ID="TextBox1" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Business Partner Name :
<asp:TextBox ID="TextBox2" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Address :
<asp:TextBox ID="TextBox3" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
Contact Person Name :
<asp:TextBox ID="TextBox4" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
<asp:TextBox ID="TextBox5" runat="server" ></asp:TextBox>
</p>
<p>
<asp:TextBox ID="TextBox6" runat="server" ></asp:TextBox>
</p>
<p>
<asp:TextBox ID="TextBox7" runat="server" ></asp:TextBox>
</p>
</asp:Content>
Code behind Code.
protected void LoadOptions()
{
DataTable CardCode = new DataTable();
SqlConnection connection = new SqlConnection("my connection string");
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT CardCode,CardName, Address, CntctPrsn FROM OCRD", connection);
adapter.Fill(CardCode);
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
id = CardCode.Rows[i]["CardCode"].ToString();
name = CardCode.Rows[i]["CardName"].ToString();
newName = id + " ---- " + name;
DropDownList1.Items.Add(new ListItem(newName,id));
}
}
}
}
.Aspx Code
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="StackOver._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</h2>
<br />
<br />
<p>
</p>
<p>
</p>
<p>
Business Partner Code :
<asp:TextBox ID="TextBox1" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Business Partner Name :
<asp:TextBox ID="TextBox2" runat="server" Width="192px" ></asp:TextBox>
</p>
<p>
Address :
<asp:TextBox ID="TextBox3" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
Contact Person Name :
<asp:TextBox ID="TextBox4" runat="server" Width="196px" ></asp:TextBox>
</p>
<p>
<asp:TextBox ID="TextBox5" runat="server" ></asp:TextBox>
</p>
<p>
<asp:TextBox ID="TextBox6" runat="server" ></asp:TextBox>
</p>
<p>
<asp:TextBox ID="TextBox7" runat="server" ></asp:TextBox>
</p>
The website I am building holds 571 houses with information about each house. Each house has a image associated with it. The information is coming from a SQL database table called houses. I am using a custom pager to filter the 571 houses with 5 results per page. I am using a repeater control to do this so I don't have multiple aspx pages. My question is I want to store the folder with the 571 images in a location (stored on a network drive) and set a path to the specific image in that folder for each house in the database table column called image and display the images for each house while using the repeater control. I have looked at a lot of tutorials but nothing is helping me. Please don't post any links to tutorials because I have looked at them all. If you have done anything like this before please post your experience because this is new to me. Source code below.
Database Structure
[Id] NCHAR (10) NOT NULL,
[Name] NVARCHAR (MAX) NULL,
[Townland] NVARCHAR (MAX) NULL,
[Near] NVARCHAR (MAX) NULL,
[Status] NVARCHAR (MAX) NULL,
[Built] NVARCHAR (MAX) NULL,
[Description] NVARCHAR (MAX) NULL,
[Families] NVARCHAR (MAX) NULL,
[Image] VARCHAR (200) NULL,
CONSTRAINT [PK_Houses] PRIMARY KEY CLUSTERED ([Id] ASC)
Example Table Data
Houses.aspx
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#expanderHead").click(function () {
$("#expanderContent").slideToggle();
if ($("#expanderSign").text() == "+") {
$("#expanderSign").html("-")
}
else {
$("#expanderSign").text("+")
}
});
});
</script>
<script>
$(function () { setCurrentTab('tab2'); });
</script>
<div class="box">
<div>
<div class="body">
<h1>Search Houses</h1>
<p>
Welcome to Houses of Mayo search page. Enter details below to search for a specific house. Additionally you can use advanced search or search by map.
</p>
<div>
<form style="margin-left: 32%">
Name of House:
<input type="search" placeholder="Search" style="margin-left: 7%">
</form>
<br />
<form style="margin-left: 32%">
Townland:
<input type="search" placeholder="Search" style="margin-left: 14%">
</form>
<br />
<form style="margin-left: 32%">
Near:
<input type="search" placeholder="Search" style="margin-left: 20%">
</form>
<br />
<form style="margin-left: 32%"><a id="expanderHead" style="cursor: pointer;">Advanced Search</a><input type="button" value="Search" class="button" style="margin-left: 35%" /></form>
<div id="expanderContent" style="display: none">
<br />
<form style="margin-left: 32%">
Associated Families:
<input type="search" placeholder="Search" style="margin-left: 2%">
</form>
<br />
<form style="margin-left: 32%">
Keyword:
<input type="search" placeholder="Search" style="margin-left: 15%">
</form>
<br />
</div>
</div>
<br />
<br />
<br />
<h1>Houses By Alphabetical Order</h1>
<ul id="rooms">
<asp:Repeater ID="rptData" runat="server">
<ItemTemplate>
<li>
<a href='<%# "HouseInfo.aspx?HouseId=" + Eval("Id").ToString() %>'>
<img src="" alt="img" width="398" height="287"/></a>
<h2>
<a href='<%# "HouseInfo.aspx?HouseId=" + Eval("Id").ToString() %>'>
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label></a></h2>
<p>
<b>ID: </b>
<asp:Label runat="server" Text='<%# Eval("Id") %>'></asp:Label>
<br />
<b>Name of House: </b>
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<br />
<b>Townland: </b>
<asp:Label runat="server" Text='<%# Eval("Townland") %>'></asp:Label>
<br />
<b>Near: </b>
<asp:Label runat="server" Text='<%# Eval("Near") %>'></asp:Label>
<br />
<b>Status/Public Access: </b>
<asp:Label runat="server" Text='<%# Eval("Status") %>'></asp:Label>
<br />
<b>Date Built: </b>
<asp:Label runat="server" Text='<%# Eval("Built") %>'></asp:Label>
</p>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
<asp:Repeater ID="rptPager" runat="server">
<ItemTemplate>
<asp:LinkButton ID="lnkPage" runat="server" Text='<%#Eval("Text") %>' CommandArgument='<%# Eval("Value") %>'
Style="padding: 8px; margin: 2px; background: #ac9e94; border: solid 1px #666; font: 8pt; color: #594334; display: inline-block;"
CssClass='<%# Convert.ToBoolean(Eval("Enabled")) ? "page_enabled" : "page_disabled" %>'
OnClick="Page_Changed" OnClientClick='<%# !Convert.ToBoolean(Eval("Enabled")) ? "return false;" : "" %>'></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
</div>
</div>
</div>
</asp:Content>
Houses.aspx.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace Houses_of_Mayo.images
{
public partial class Houses : System.Web.UI.Page
{
private int PageSize = 5;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.GetHousesPageWise(1);
}
}
private void GetHousesPageWise(int pageIndex)
{
string constring = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("GetHousesPageWise", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#PageIndex", pageIndex);
cmd.Parameters.AddWithValue("#PageSize", PageSize);
cmd.Parameters.Add("#RecordCount", SqlDbType.Int, 4);
cmd.Parameters["#RecordCount"].Direction = ParameterDirection.Output;
con.Open();
IDataReader idr = cmd.ExecuteReader();
rptData.DataSource = idr;
rptData.DataBind();
idr.Close();
con.Close();
int recordCount = Convert.ToInt32(cmd.Parameters["#RecordCount"].Value);
this.PopulatePager(recordCount, pageIndex);
}
}
}
private void PopulatePager(int recordCount, int currentPage)
{
double dblPageCount = (double)((decimal)recordCount / Convert.ToDecimal(PageSize));
int pageCount = (int)Math.Ceiling(dblPageCount);
List<ListItem> pages = new List<ListItem>();
if (pageCount > 0)
{
for (int i = 1; i <= pageCount; i++)
{
pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
}
}
rptPager.DataSource = pages;
rptPager.DataBind();
}
protected void Page_Changed(object sender, EventArgs e)
{
int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
this.GetHousesPageWise(pageIndex);
}
public override void VerifyRenderingInServerForm(Control control)
{
return;
}
}
}
Store Procedure
CREATE PROCEDURE GetHousesPageWise
#PageIndex INT = 1
,#PageSize INT = 5
,#RecordCount INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER
(
ORDER BY [Name] ASC
)AS RowNumber
,[Id]
,[Name]
,[Townland]
,[Near]
,[Status]
,[Built]
INTO #Results
FROM [Houses]
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
end
Houses.aspx
Change stored procedure's select query
SELECT ROW_NUMBER() OVER
(
ORDER BY [Name] ASC
)AS RowNumber
,[Id]
,[Name]
,[Townland]
,[Near]
,[Status]
,[Built]
,[Image]
INTO #Results
FROM [Houses]
and use
<img src='<%# Eval("Image") %>' alt="img" width="398" height="287"/>
First of all I advice to bind to datasource by using NetTiers model like this
and then you use Eval as this
"> />
I have Image in ItemTemplate that will be changing according to Username (ie lblPostedBy.Text). I have written code in onItemCommand of repeater control in C# Asp.net 4.0. But not working. Will you please help me.
protected void myrepeater_ItemCommand1(object source, RepeaterCommandEventArgs e)
{
// Actually lblPostedBy is a linkbutton and lblPostedBy.Text is 'username of the commenter'.
LinkButton lblPostedBy = (LinkButton)e.Item.FindControl("lblPostedBy");
con.Open();
cmd.CommandText = "select image from " + lblPostedBy.Text + " where id=1";
// 'image' column in table stores path of image like '~/image/image1.jpg'
cmd.Connection = con;
string imageurl = (string)cmd.ExecuteScalar();
con.Close();
Image Image1 = (Image)e.Item.FindControl("Image1");
Image1.ImageUrl = imageurl;
}
and
<asp:Repeater ID="myrepeater" runat="server"
onitemcommand="myrepeater_ItemCommand1">
<HeaderTemplate>
<table width="100%" style="font: 8pt verdana">
<tr style="background-color:#3C78C3">
<th>NEWS FEED</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td valign="top">
<asp:Image ID="Image1" runat="server" Height="50px" Width="50px" />
<asp:LinkButton ID="lblPostedBy" runat="server" onclick="lblPostedBy_Click" Text='<%#DataBinder.Eval(Container,"DataItem.postedby") %>' />   says : <br />
<asp:TextBox id="txtPost" runat="server" Width="100%" textmode="multiline" text='<%#DataBinder.Eval(Container,"DataItem.scraps")%>' ReadOnly="True" BackColor="#EFF3FB" BorderStyle="None"></asp:TextBox>
<%#DataBinder.Eval(Container,"DataItem.scraptime") %>
<br />
<asp:TextBox ID="TextBox2" runat="server" Visible="False" Width="80%"></asp:TextBox>
<asp:Button ID="btnDoneComment" runat="server" Text="Done" Visible="False" onclick="btnDoneComment_Click"/>
<br />
<hr style="border:dashed 1px blue" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Thanks in Advance,
Regards,
Nikhil
Instead of "cmd.CommandText = "select image from " + lblPostedBy.Text;"
Shouldn't it be
cmd.CommandText = "select image from TableName where pby = '" + lblPostedBy.Text + "'";
Better yet, add a parameter
cmd.CommandText = "select image from tablename where pby = #pby"
cmd.Parameters.Add(new SalParameter("#pby", lblPostedBy.Text);