I'm creating a asp.net website for showing up rss feed from BBC, I'm doing exactly as i want that i m showing the rss feed on asp:DataList but my problem is that i dont want to show feed directly from a XML document, i want to store it firstly to my database and then show it to my website using Datalist. My older code is
<asp:DataList ID="DataList1" runat="server" DataSourceID="XmlDataSource1">
<ItemTemplate>
<div class="jumbotron">
<h2><%# XPath("title") %></h2>
<br />
<h3><%# XPath("pubDate") %></h3>
<br />
<h3><%# XPath("description") %></h3>
<br />
<asp:Repeater runat="server" ID="_subitemsRepeater"
EnableViewState="false"
DataSource='<%# XPathSelect("media:thumbnail", XmlNamespaceManager) %>'>
<ItemTemplate>
<img src="<%# ((System.Xml.XmlNode)Container.DataItem).Attributes["url"].Value %>" />
<br />
</ItemTemplate>
</asp:Repeater>
<br />
<a class="btn btn-primary btn-lg" target="_blank" href="<%# XPath("link") %>">Read More On This Story</a>
</div>
<hr />
</ItemTemplate>
</asp:DataList>
<asp:XmlDataSource ID="XmlDataSource1" runat="server"
DataFile="http://feeds.bbci.co.uk/news/education/rss.xml"
XPath="rss/channel/item" />
C# Code is in page load
public partial class _Default : Page
{
protected XmlNamespaceManager XmlNamespaceManager { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
XmlNamespaceManager = new XmlNamespaceManager(XmlDataSource1.GetXmlDocument().NameTable);
XmlNamespaceManager.AddNamespace("media", "http://search.yahoo.com/mrss/");
}
}
and my new code is:
FileWebRequest rssFeed = (FileWebRequest)WebRequest.Create(FeedURL);
// DataSet rssData = new DataSet();
//read the xml from the stream of the web request
XDocument xd = XDocument.Load(rssFeed.GetResponse().GetResponseStream());
XNamespace media = "http://feeds.mashable.com/Mashable?format=xml";
foreach (var feed in xd.Descendants("item"))
{
string title = feed.Element("title").Value.ToString();
string description = feed.Element("description").Value.ToString();
string link = feed.Element("link").Value.ToString();
DateTime pubdate = DateTime.Parse(feed.Element("pubDate").Value);
string thumb = (string)feed.Element(media + "thumbnail") != null ? (string)feed.Element(media + "thumbnail").Attribute("url").Value.ToString() : "file:///c:/No_Image.png";
string connection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
SqlConnection NewCon = new SqlConnection(connection);
NewCon.Open();
SqlCommand NewCMD = new SqlCommand(TableName + "_Proc", NewCon);
NewCMD.CommandType = CommandType.StoredProcedure;
NewCMD.Parameters.AddWithValue("#title", title);
NewCMD.Parameters.AddWithValue("#description", description);
NewCMD.Parameters.AddWithValue("#link", link);
NewCMD.Parameters.AddWithValue("#pubdate", pubdate);
NewCMD.Parameters.AddWithValue("#thumb", thumb);
NewCMD.ExecuteNonQuery();
NewCon.Close();
}
in this code the problem is with images that it returns me the NoImage.jpg every time I'm connected to the internet. I think there is no problem with NameSpace too.
I'm doing it because if the feed server or news server shutdown or not respond then my website not effected so. Anybody know how resolve this issue?. Any help will be greatly appreciated. thanks !
Related
This is my first post here and I am new to programming. Right now, I am trying to changing column name in the DataTable which the data is fetch from the sql database. After I changing the column name using a foreach loop, it appears that after i change the column name of the datatable, the program crash right after I bind it to the gridview.
the error occur
Any idea what is causing the error?
C# code behind:
//custom query generator
Session["query"] = db.generate_query(parameter1, parameter2, parameter3, parameter4);
//connecting sql
SqlConnection conn = new SqlConnection("Data Source=USER-PC;Initial Catalog=ISMS;Integrated Security=True");
SqlCommand cmd1 = new SqlCommand(Session["query"].ToString(),conn);
SqlDataAdapter sdal = new SqlDataAdapter(cmd1);
//when search is needed
dt_table = new DataTable();
sdal.Fill(dt_table);
// dataTable.Columns["ExistingColumnName"].ColumnName = "regnum";
//renaming column in datatable
foreach (DataColumn dtclm in dt_table.Columns) {
dt_table.Columns[dtclm.ToString()].ColumnName = dt_table.Columns[dtclm.ToString()].ColumnName.ToString().Replace("_"," ");
}
staff_attendance_gridview.Visible = true;
staff_attendance_gridview.DataSource = dt_table;
staff_attendance_gridview.DataBind();
result_message.Text = dt_table.Rows.Count.ToString() + " rows in the table";
the aspx file:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="admin_attendance_.aspx.cs" Inherits="ISMS.admin_attendance" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<!--start container box-->
<div id="container_box">
<div id="text">
<asp:Label runat="server" ID="welcome_message" /><br />
<br />
<!--search bar-->
<p>
<br />
Employee ID: <asp:TextBox runat="server" ID="employee_search" Text="" /><br />
<br />
Attendance ID: <asp:TextBox runat="server" ID="attendance_ID_text_box" Text="" /><br />
<br />
fill up both attendance ID and Employee ID and click delete to delete certain record.<br />
<br />
<asp:Button ID="search_btn" runat="server" Text="search" OnClick="search_btn_Click" />
<asp:Button ID="clock_in_or_out_btn" runat="server" Text="clock in/out" OnClick="clock_in_or_out_btn_Click" />
<asp:Button ID="delete_button" runat="server" Text="delete" OnClick="delete_button_Click" />
<br />
</p>
<!--gridview-->
<hr />
<br />
<div id="gridview">
<asp:GridView runat="server" ID="staff_attendance_gridview" OnPageIndexChanging="gridview_PageIndexChanging" AutoGenerateColumns="true" DataKeyNames="Attendance_id" >
</asp:GridView>
</div>
<!--end gridview-->
<p>
<!--validator-->
<asp:RegularExpressionValidator ID="employee_search_validator" runat="server"
ErrorMessage="Invalid searching citeria. Only exactly 8 numbers is allowed."
ControlToValidate="employee_search"
ValidationExpression="^[0-9]{8}$" /><br />
<br />
</p>
<br />
<!--hyperlink to main menu-->
<asp:Label runat="server" ID="result_message" /><br />
<a href="admin.aspx" >Main menu</a>
</div>
</div>
<!--end container box-->
</asp:Content>
Database table structure
You have an attribute in your GridView that refers to a column Attendance_id. That must match the updated name of your column Attendance id.
I've corrected your code below to properly handle IDisposable and remove overly complex bits.
Session["query"] = db.generate_query(parameter1, parameter2, parameter3, parameter4);
using(SqlConnection conn = new SqlConnection("Data Source=USER-PC;Initial Catalog=ISMS;Integrated Security=True"))
{
using(SqlCommand cmd1 = new SqlCommand(Session["query"].ToString(), conn))
{
using(SqlDataAdapter sdal = new SqlDataAdapter(cmd1))
{
dt_table = new DataTable();
sdal.Fill(dt_table);
}
}
}
foreach (DataColumn column in dt_table.Columns)
{
column.ColumnName = column.ColumnName.Replace("_", " " );
}
staff_attendance_gridview.Visible = true;
staff_attendance_gridview.DataSource = dt_table;
staff_attendance_gridview.DataBind();
result_message.Text = dt_table.Rows.Count + " rows in the table";
I am using Ajax with asp.net C#. What I am trying to do is, on click of a link, a div should appear. A div contains file upload controls and a button named 'Upload Files'. When upload files button is clicked, it is checking if any of the file upload controls has files. If yes, it uploads files to some directory and updates a label to show how many files are uploaded 0 or more. Here is the screenshot to explain:
Here's the code snippet, I am using Ajax with asp.net C#
<div class="form-group row">
<asp:UpdatePanel runat="server" id="UpdatePanel1" updatemode="Conditional">
<ContentTemplate>
<div class="col-xs-5">
<% if (Session["MemberID"]!= null)
{%>
<asp:LinkButton ID="insertMore" runat="server" OnClick="insertMoreclicked">(Insert More Attachments)</asp:LinkButton>
<%} %>
</div><br />
<div id="moreUploadsDiv" runat="server" visible="false">
<br />
<asp:FileUpload ID="moreUpload1" runat="server" />
<asp:FileUpload ID="moreUpload2" runat="server" />
<asp:FileUpload ID="moreUpload3" runat="server" />
<asp:FileUpload ID="moreUpload4" runat="server" />
<asp:Button ID="uploadMoreFilesBtn" runat="server" Text="Upload" OnClick ="uploadMoreClicked" CausesValidation="false" />
<br />
<asp:Label ID="uploadInfoLbl" runat="server" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
Here's the code behind file event for button:
protected void uploadMoreClicked(object sender, EventArgs e)
{
int countFiles = 0;
if (moreUpload1.HasFile)
{
moreUpload1.PostedFile.SaveAs(Server.MapPath("/Upload/") + moreUpload1.FileName);
string fn2 = moreUpload1.FileName;
bool status2 = blReg.insertFiles(fn2, FileID);
countFiles++;
}
if (moreUpload2.HasFile)
{
moreUpload2.PostedFile.SaveAs(Server.MapPath("/Upload/") + moreUpload2.FileName);
string fn2 = moreUpload2.FileName;
bool status2 = blReg.insertFiles(fn2, FileID);
countFiles++;
}
if (moreUpload3.HasFile)
{
moreUpload3.PostedFile.SaveAs(Server.MapPath("/Upload/") + moreUpload3.FileName);
string fn2 = moreUpload3.FileName;
bool status2 = blReg.insertFiles(fn2, FileID);
countFiles++;
}
if (moreUpload4.HasFile)
{
moreUpload4.PostedFile.SaveAs(Server.MapPath("/Upload/") + moreUpload4.FileName);
string fn2 = moreUpload4.FileName;
bool status2 = blReg.insertFiles(fn2, FileID);
countFiles++;
}
uploadInfoLbl.Text = countFiles + " file(s) uploaded<br/>";
}
But button click event doesn't work. Please suggest me what i am doing wrong. Thanks in Advance!
In .aspx page , I’ve taken Label Control in order to display question form the database,
4 radio buttons in order to display four option related to a particular question, and last but not the least, I’ve used hidden field in which I will store answer of the particular question.
And finally I’ve taken a Button Control, for which I’ve created the onclick event, on which I will perform the operation to generate score.
In .aspx.cs page, on the onclick event of the button, , I’ve fetch the controls form the aspx page using code mentioned below, and further I’ve used if statement in order to see which radio button is active and have store the corresponding value in the varialbe “selans”, using this “selans”, I will compare it with the value of hidden field in order to find whether checked radio button is the correct answer or not, it the answer is correct, i.e value in “selans” matches with the value in hidden field ( the actual answer) and the variable “count” ( initially initialized with value 0) increments accordingly, and all this code is placed in the “for loop” which will execute till the no. of controls in the GridView (you can relate it with the no. of question, as for every record GridView generates new control).
But when I run it I am getting this error :-
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Optiont4'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Optiont4'.
Source Error:
Line 115: <asp:RadioButton ID="rad2" runat="server" Text='<%#Eval("Option2") %>' GroupName="A" />
Line 116: <asp:RadioButton ID="rad3" runat="server" Text='<%#Eval("Option3") %>' GroupName="A" />
Line 117: <asp:RadioButton ID="rad4" runat="server" Text='<%#Eval("Optiont4")%>' GroupName="A" />
Line 118: <asp:HiddenField ID="hf" runat="server" Value='<%#Eval("CorrectAns")%>' />
Line 119:
Source File: e:\Way2Success\Student\Examdemo.aspx Line: 117
Here the error line number is 30 in .aspx page
Have a look at my code. Show me were I am making mistaking and what is the solution.
.aspx :-
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Examdemo.aspx.cs" Inherits="Student_Examdemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form2" runat="server">
<div>
<div id="tabs">
<ul>
<li>Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
<li>Tab 4</li>
<li>Tab 5</li>
</ul>
<div id="tabs-1">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Question") %>'></asp:Label>
<br />
<br />
<br />
<asp:RadioButton ID="rad1" runat="server" Text='<%#Eval("Option1") %>' GroupName="A" />
<asp:RadioButton ID="rad2" runat="server" Text='<%#Eval("Option2") %>' GroupName="A" />
<asp:RadioButton ID="rad3" runat="server" Text='<%#Eval("Option3") %>' GroupName="A" />
<asp:RadioButton ID="rad4" runat="server" Text='<%#Eval("Option4") %>' GroupName="A" />
<asp:HiddenField ID="hf" runat="server" Value='<%#Eval("CorrectAns") %>' />
<br />
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div id="tabs-2">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Question") %>'></asp:Label>
<br />
<br />
<br />
<asp:RadioButton ID="rad1" runat="server" Text='<%#Eval("Option1") %>' GroupName="A" />
<asp:RadioButton ID="rad2" runat="server" Text='<%#Eval("Option2") %>' GroupName="A" />
<asp:RadioButton ID="rad3" runat="server" Text='<%#Eval("Option3") %>' GroupName="A" />
<asp:RadioButton ID="rad4" runat="server" Text='<%#Eval("Optiont4")%>' GroupName="A" />
<asp:HiddenField ID="hf" runat="server" Value='<%#Eval("CorrectAns")%>' />
<br />
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div id="tabs-3">
Tab 3 Content
</div>
<div id="tabs-4">
Tab 4 Content
</div>
<div id="tabs-5">
Tab 5 Content
</div>
</div>
<input type="button" id="btnPrevious" value="Previous" style = "display:none"/>
<input type="button" id="btnNext" value="Next" />
<asp:Button class="panelButton" runat="server" Text="Finish the exam" ClientIDMode="Static" OnClick="btn_Click" />
<br />
</div>
</form>
</body>
</html>
.aspx.cs :-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class Student_Examdemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData("SELECT top 2 Question, Option1, Option2, Option3, Option4, CorrectAns, Explanation FROM Questions");
GridView1.DataBind();
GridView2.DataSource = GetData("SELECT top 2 Question, Option1, Option2, Option3, Option4, CorrectAns, Explanation FROM Questions WHERE SectionId=2");
GridView2.DataBind();
private DataSet GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
protected void btn_Click(object sender, EventArgs e)
{
RadioButton r1, r2, r3, r4;
HiddenField hdn;
int count = 0;
int neg = 0;
int total;
int totalf=0;
int totals=0;
int totalt;
int totalfo;
int totalfi;
string selans = "-1";
for (int i = 0; i < GridView1.Rows.Count; i++)
{
r1 = (RadioButton)GridView1.Rows[i].Cells[0].FindControl("rad1");
r2 = (RadioButton)GridView1.Rows[i].Cells[0].FindControl("rad2");
r3 = (RadioButton)GridView1.Rows[i].Cells[0].FindControl("rad3");
r4 = (RadioButton)GridView1.Rows[i].Cells[0].FindControl("rad4");
hdn = (HiddenField)GridView1.Rows[i].Cells[0].FindControl("hf");
if (r1.Checked)
{
selans = r1.Text;
}
else if (r2.Checked)
{
selans = r2.Text;
}
else if (r3.Checked)
{
selans = r3.Text;
}
else if (r4.Checked)
{
selans = r4.Text;
}
if (hdn.Value == selans)
{
count++;
}
else
{
neg--;
}
totalf = count + neg;
}
for (int i = 0; i < GridView2.Rows.Count; i++)
{
r1 = (RadioButton)GridView2.Rows[i].Cells[0].FindControl("rad1");
r2 = (RadioButton)GridView2.Rows[i].Cells[0].FindControl("rad2");
r3 = (RadioButton)GridView2.Rows[i].Cells[0].FindControl("rad3");
r4 = (RadioButton)GridView2.Rows[i].Cells[0].FindControl("rad4");
hdn = (HiddenField)GridView2.Rows[i].Cells[0].FindControl("hf");
if (r1.Checked)
{
selans = r1.Text;
}
else if (r2.Checked)
{
selans = r2.Text;
}
else if (r3.Checked)
{
selans = r3.Text;
}
else if (r4.Checked)
{
selans = r4.Text;
}
if (hdn.Value == selans)
{
count++;
}
else
{
neg--;
}
totals = count + neg;
}
total = totalf + totals;
Session["score"] = total;
}
}
You have a typing error in your GridView2 definition.
<asp:RadioButton ID="rad4" runat="server" Text='<%#Eval("Optiont4")%>' GroupName="A" />
should be
<asp:RadioButton ID="rad4" runat="server" Text='<%#Eval("Option4")%>' GroupName="A" />
I get the following error in a page:
'The name 'DataList1' does not exist in the current context'
Here is my code:
listviewvideo.aspx.cs
private void BindGrid()
{
string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, Name from uploadvideo";
cmd.Connection = con;
con.Open();
DataList1.DataSource = cmd.ExecuteReader();
DataList1.DataBind();
con.Close();
}
}
}
listviewvideo.aspx
<table>
<tr>
<td>
<ASPNetFlashVideo:FlashVideo ID="FlashVideo1" runat="server" Height="500" Width="1050"></ASPNetFlashVideo:FlashVideo>
<asp:FileUpload ID="FileUpload1" runat="server" CssClass="myButton" />
<asp:Button ID="btnupload" runat="server" Text="Upload" OnClick="btnupload_Click" CssClass="myButton" />
<hr />
<asp:DataList ID="DataList1" Visible="true" runat="server" AutoGenerateColumns="false" RepeatColumns="2" CellSpacing="5">
<ItemTemplate>
<u>
<%# Eval("Name") %>
</u>
<a class="player" style="height:300px; width:300px; display:block" href='<%# Eval("Id","FileCS.ashx?Id={0}") %>'></a>
</ItemTemplate>
</asp:DataList>
</td>
</tr>
</table>
I get the following error in a page:
'The name 'DataList1' does not exist in the current context'
You might get this error. There 3 solutions for this
Save your project and close the Solution, close the IIS Express also. And check whether it works or not.
Try adding the the datalist by writing below code in your listviewvideo.aspx.designer.cs page of where you are adding the Datalist item.
Check your code behind file name and Inherits property on the #Page directive, make sure they both match.
Also you can have a look here for more clear picture
ID Does not exist in the current context
protected global::System.Web.UI.WebControls.DataList Datalist1;
Hope this helps.
I want to some images in asp repeater which comes from databas image table.
HTML
<asp:Repeater ID="rpt_" runat="server">
<ItemTemplate>
<li>
<img src="<%="data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("Photo")) %>" alt="" />
</li>
</ItemTemplate>
</asp:Repeater>
C#
private void Load_()
{
ClassDo class_ = new ClassDo;
DataTable dt = class_.Ann().Tables[0];
rpt_.DataSource = dt;
rpt_.DataBind();
}
These are my codes, and get me error I cannot show images.
HTML
<img alt="" src="<%="data:image/jpg;base64," + Convert.ToBase64String(Class_._image) %>" />
C#
Class_._image = (byte[])dt.Rows[0]["Photo"];
It works like that somewhere else, but with repeater I cannot read it with Eval.
Is there any working way to show images?
Can you try this?
Create a function
public string GetImage(object img)
{
return "data:image/jpg;base64," + Convert.ToBase64String((byte[])img);
}
Then change your declaration like this
<asp:Image ImageUrl='<%# GetImage(Eval("Photo")) %>' />