I am trying to display multiple lines from a database into an aspx page. My aspx page name is news.aspx and my table is called news.
I have configured my aspx with the code to display what I want my page to look like. I have attached an image to show I would like it to look like when the page is loaded. The aspx page uses ItemTemplate & asp:Repeater to display the multiple lines.
My aspx page is configured as follows:
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="col-lg-12">
<div class="form-group alert alert-info">
<asp:label runat="server" ID="lblNewsEdits">Latest Sports & Social News Items</asp:label>
</div>
</div>
</div>
</div>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="col-lg-12">
<p>
Title:
<asp:Literal ID="litTitle" runat="server"></asp:Literal>
(<asp:Literal ID="litDatePosted" runat="server"></asp:Literal>)
</p>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="col-lg-12">
<p>
Title:
<asp:Literal ID="litNewsContent" runat="server"></asp:Literal>
</p>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
My aspx.cs page is configured to pull the information from the news table, I want three column of data to be display in the aspx page (Title, DatePosted and NewsContent).
For the three lines below, I am getting error: "The name "..." does not exist in the current context.
litTitle.text = reader ["Title"].ToString();
litDatePosted.Text = reader["Date Posted"].ToString();
litNewsContent.Text = reader["News Content"].ToString();
The aspx.cx page is configured as follows:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString);
string getNewsQuery = "SELECT Id, Title, DataPosted, Newsontent FROM News WHERE Id = #id";
//get email based on id
SqlCommand getNewsCommand = new SqlCommand(getNewsQuery, connection);
object id = null;
getNewsCommand.Parameters.AddWithValue("#id", id);
connection.Open();
SqlDataReader reader = getNewsCommand.ExecuteReader();
while (reader.Read())
{
litTitle.txt = reader ["Title"].ToString();
litDatePosted.Text = reader["Date Posted"].ToString();
litNewsContent.Text = reader["News Content"].ToString();
}
reader.Close();
connection.Close();
}
My database table is configured as follows:
CREATE TABLE [dbo].[News] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Title] NVARCHAR (100) NOT NULL,
[DatePosted] DATE NOT NULL,
[NewsContent] NTEXT NOT NULL,
[IsRead] BIT DEFAULT ((0)) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)[![enter image description here][1]][1]
);
Any ideas?
Try to format your code like this:
litTitle.txt = reader["Title"].ToString();
litDatePosted.Text = reader["DatePosted"].ToString();
litNewsContent.Text = reader["NewsContent"].ToString();
Also in your sql query you have a typo in the SELECT statement, you typed
'Newsontent' instead of 'NewsContent'
EDIT:
Try using the grid view instead of table. GridView should format it selfe acording to the sorce provided by the SqlDataAdapter
protected void Pageaaa_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString);
string getNewsQuery = "SELECT Id, Title, DataPosted, Newsontent FROM News WHERE Id = #id";
//get email based on id
SqlCommand getNewsCommand = new SqlCommand(getNewsQuery, connection);
object id = null;
getNewsCommand.Parameters.AddWithValue("#id", id);
connection.Open();
SqlDataReader reader = getNewsCommand.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dataTable = new DataTable();
da.Fill(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
connection.Close();
da.Dispose();
}
Related
I have a database that contains all the lastest news. I want the homepage to only display the latest three news items.
My aspx page is setup as:
<div class="row">
<asp:Repeater ID="rptNewsList" runat="server">
<ItemTemplate>
<div class="col-md-4">
<h2><%# Eval("Title") %>
<small><%# Eval("NewsContent") %></small>
</h2>
</div>
<div class="col-md-4">
<h2><%# Eval("Title") %>
<small><%# Eval("NewsContent") %></small>
</h2>
</div>
<div class="col-md-4">
<h2><%# Eval("Title") %>
<small><%# Eval("NewsContent") %></small>
</h2>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
My aspx.cs page is setup as follows, I am using a repeater and the repeater loads the same news into the three columns
I would like col 1 to have latest news and col 2 to have latest news -1 and col 3 to have latest news -2
protected void Page_Load(object sender, EventArgs e)
{
rptNewsList.DataSource = GetNewsList();
rptNewsList.DataBind();
}
private DataTable GetNewsList()
{
DataTable dataTable = new DataTable();
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString);
string query = "SELECT top 1 [Id], [Title], [DatePosted], [NewsContent] FROM [News] ORDER BY [Id] DESC";
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
dataTable.Load(command.ExecuteReader());
connection.Close();
return dataTable;
}
My table is configured as follows:
CREATE TABLE [dbo].[News] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Title] NVARCHAR (100) NOT NULL,
[DatePosted] DATE NOT NULL,
[NewsContent] NTEXT NOT NULL,
[IsRead] BIT DEFAULT ((0)) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
I think you may need to change your query to something like this:
SELECT DISTINCT TOP 3 [Id], [Title], [DatePosted], [NewsContent] FROM [News]
ORDER BY [DatePosted] DESC
I am trying to retrieve product information such as name,imagepath etc from database using repeater and display in the dataview using code behind. I could successfully retrieve and display the detail but the alignment of the div is not proper.
aspx code:
<div class="row">
<asp:Repeater ID="Repeater2" runat="server"></asp:Repeater>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div class="col-sm-4 col-lg-4 col-md-4">
<div class="thumbnail">
<img width="250px" height="300px" src="images/<%#Eval("ImagePath") %>" alt="<%#Eval("ProductName") %>">
<div class="caption">
<h4><%#Eval("ProductName") %></h4>
<h4><%#Eval("UnitPrice")%></h4>
</div>
<div class="clearfix">
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
code behind:
SqlDataAdapter sda = new SqlDataAdapter("SELECT ProductName, UnitPrice, ImagePath FROM Products", con);
DataTable dt = new DataTable();
sda.Fill(dt);
DataView dv = new DataView(dt);
dv.Sort = "ProductName"; // Sort by product name
Repeater1.DataSource = dv;
Repeater1.DataBind();
current output:
screenshot
Expected output:
The fourth image should come below the first image according to bootstrap gridview concept which is not happening in my case and because of which the entire layout changes.
I am a beginner and have just started to learn bootstrap.
There are two ways to resolve this issue:
1) End the row after 3 columns and start 2nd row for next 3 columns.
2) Add equal height for columns. You can use following script and add 'resize-height' class to each column.
function setHeight(column) {
var maxHeight = 0;
//Get all the element with class = col
column = jQuery(column);
column.css('height', 'auto');
//Loop all the column
column.each(function () {
//Store the highest value
if (jQuery(this).height() > maxHeight) {
maxHeight = jQuery(this).height();
}
});
//Set the height
column.height(maxHeight);
}
jQuery(window).on('load resize', function () {
setHeight('.resize-height');
});
I am a new in coding asp.net and vb.net. I have a web form built with asp.net and vb.net .
In the front end of the there are four fields constructed as below.
Recipient Mailing List : Drop down List (the options in the drop down list are such as Managers, HR, Admin, IT etc. Each option name contains multiple email addresses. i.e selecting one option means The user selects one group of of email address in the recipient field )
From Field : Text box (Read Only )
Subject : Text box
Message : Textarea
Send email button
The asp.net front end code is like below.
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">
<div class="aux-body">
<div class="aux-body-content">
<div class="form-element">
<label>Recipient Mailing list </label>
<select runat="server" class="" id="comMailingList" datatextfield="name" datavaluefield="id"></select>
</div>
<div class="form-element">
<label> From </label>
<input style="width: 98%;" runat="server" id="txtFrom" type="text" value="Careers portal" readonly="readonly" />
</div>
<div class="form-element">
<label> Subject </label>
<input style="width: 98%;" runat="server" id="txtSubject" class="msubject" type="text" />
</div>
<div class="form-element">
<label> Message </label>
<textarea style="width: 98%; height: 100px;" runat="server" id="txtText" ></textarea>
</div>
<div id="button-group">
<asp:LinkButton runat="server" ID="btnSend" CssClass="btn" Text="Send Email"></asp:LinkButton>
</div>
</div>
</div>
</asp:Content>
In the back end i have structured the VB.net code like following. But i am unable to write the code that will send the email.
Partial Class E4_Candidate_broadcast
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
If Not IsNothing(Request("b")) Then
cid.Value = Request("b")
End If
litMyEmail.Text = UserEmail
comMailingList.DataSource = Lists
comMailingList.DataBind()
End If
End Sub
Public ReadOnly Property Lists() As DataTable
Get
Return DB.GetData("select ml.id, ml.name + ' (' + cast( count(mlc.mailinglistid) as nvarchar(10)) + ' contacts)' name from mailinglist ml join mailinglistcontact mlc on ml.id = mlc.mailinglistid where ml.deleted = 0 and ml.createdby in (select userid from employeruser where employerid = #eid) group by ml.id, ml.name having count(mlc.mailinglistid) > 0 order by ml.name", DB.SIP("eid", LocalHelper.UserEmployerID()))
End Get
End Property
Protected Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
If Not String.IsNullOrWhiteSpace(txtSubject.Value) Then
''Selects the recipients name and email address
Dim contacts = DB.GetData("select title, name, surname, email from mailinglistcontact where mailinglistid = #mlid", DB.SIP("mlid", comMailingList.Value)), _
mailers = New DataTable(), _
mailerqueue = New DataTable(), _
scheduleat = Now
For Each contact As DataRow In contacts.Rows
''''Code for sending email''''
Next
Response.Redirect("broadcast-sent-complete.aspx?i=" & cbId)
End If
End Sub
End Class
I have seen several examples by googling and found several links. But I am surely not understanding many things which are essential to code for sending emails.
I will be very much obliged if you help me write the code to send emails.
Thank you
Update
I have tried the following code. but its not working. i.e. the email is not sending.the code is going to the exception and saying message sending mailed. please have a look at my code and point me my error.
Dim message As New MailMessage()
For Each contact As DataRow In contacts.Rows
Try
Dim Client As New System.Net.Mail.SmtpClient
With Client
If WebConfigurationManager.AppSettings("smtpserver").Length > 0 Then
.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory 'Net.Mail.SmtpDeliveryMethod.Network
.PickupDirectoryLocation = "c:/outbox/"
.Host = WebConfigurationManager.AppSettings("smtpserver")
Else
.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.PickupDirectoryFromIis
End If
With message
Dim FromAddress As MailAddress = New MailAddress("noreply#mypeoplebiz.com")
.From = FromAddress
.[To].Add(contact.Item("email").ToString())
.Subject = txtSubject.Value
.IsBodyHtml = True
.Priority = MailPriority.Normal
.BodyEncoding = Encoding.Default
If Not String.IsNullOrWhiteSpace(txtHtml.Value) Then
.Body = txtHtml.Value
End If
If Not String.IsNullOrWhiteSpace(txtText.Value) Then
.Body = txtText.Value
End If
End With
.Send(message)
End With
Catch Ex As Exception
_error = Ex.Message
End Try
Next
I am trying to insert an image into database with its properties and a couple of textboxes. Here is the HTML code:
<span class="label"><label for="FirstName">First Name: </label></span>
<asp:TextBox ID="FirstName" runat="server"></asp:TextBox>
</div>
<div class="row">
<span class="label"><label for="Surname">Surname: </label></span>
<asp:TextBox ID="Surname" runat="server"></asp:TextBox>
</div>
<div class="row">
<span class="label"><label for="PhotoUpload">Photo: </label></span>
<asp:FileUpload ID="PhotoUpload" runat="server" />
</div>
<div class="row">
<span class="label"> </span>
<asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" />
The code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
if (PhotoUpload.HasFile)
{
Stream photoStream = PhotoUpload.PostedFile.InputStream;
int photoLength = PhotoUpload.PostedFile.ContentLength;
string photoMime = PhotoUpload.PostedFile.ContentType;
string photoName = Path.GetFileName(PhotoUpload.PostedFile.FileName);
byte[] photoData = new byte[photoLength - 1];
photoStream.Read(photoData, 0, photoLength);
string CS = ConfigurationManager.ConnectionStrings["mm"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("spLogo", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FName", FirstName.Text);
cmd.Parameters.AddWithValue("#SName", Surname.Text);
cmd.Parameters.AddWithValue("#PData", photoData);
cmd.Parameters.AddWithValue("#PName", photoName);
cmd.Parameters.AddWithValue("#PLength", photoLength);
cmd.Parameters.AddWithValue("#PMime", photoMime);
cmd.ExecuteNonQuery();
}
}
What could be the problem here?
This is my stored procedure:
alter procedure spLogo
#FName nvarchar(50),
#SName nvarchar(50),
#PData VarBinary(max),
#PName nvarchar(50),
#PLength int,
#PMime nvarchar(50)
as
begin
Insert into Employee2 values(#FName,#SName,#PData,#PName,#PLength,#PMime)
END
I am working on an image for the first time so I'm not sure which datatype would be the best but this is the best code I can come up with.
This line could be the root cause, as you are creating an array of byte with length lesser than image length.
byte[] photoData = new byte[photoLength - 1];
lets say, the photolength is 1000, so you are creating byte array (photoData) of 999 size, now when the below line tries to copy 1000th byte to photoData, it will fail.
photoStream.Read(photoData, 0, photoLength);
You should create the byte array as same as Image length. Hope it works.
byte[] photoData = new byte[photoLength];
<form id="Form1" runat="server">
**<input type="text" id="DateInput" />**
<asp:Repeater ID="DataViewer" runat="server">
<ItemTemplate>
<div style='border: 1px; width: 600px; overflow-x: auto; overflow-y: hidden;'>
<div style='float: left;'>
<%# Eval("DriverName") %> </div>
</div>
</ItemTemplate>
</asp:Repeater>
this is my function:
protected void Page_Load(object sender, EventArgs e)
{
OrderDataRepository rep = new OrderDataRepository();
var results = rep.GetAllOrderData().Where(x => x.POD_DATE == ????????????????).
GroupBy(o => o.User).
Select(g =>
new
{
DriverId = g.Key.Id,
DriverName = g.Key.Name,
OrderCount = g.Count(),
OrderCountWhereNameIsNotNull =
g.Count(o => o.RECEIVE_NAME != null)
}).ToList();
DataViewer.DataSource = results;
DataViewer.DataBind();
}
at the moment i get all the results from the table,
i want to add Datepicker for jQuery http://keith-wood.name/datepick.html
<script src="Scripts/jquery.js" type="text/javascript"></script>
when user will pick a day it needs to load all the results for the day that the user picked
please show me how it should be done using jquery with entity framework
You'll need a function in your repository some thing like:
Function SelectOrdersByDate(date as string) as ienumerable(of Order)
Using yourcontext as new context
Dim query = yourcontext.Orders.Where(function(o) o.OrderDate = date).ToList
return query
End Using
End Function
Then call this function via ajax/jquery