ASP.NET VB add button that has removechild() function - asp.net

I just want to know how to add a button that has a removechild() or replacechild() function on my XML. Been searching for this for a week now.
Any suggestions would be greatly appreciated. Thanks :)
This is my xml file content
<?xml version="1.0" encoding="utf-8"?>
<theNews>
<news>
<contents>News3 Contents</contents>
<title>News3 Title</title>
<pubDate>February 13, 2012</pubDate>
</news>
<news>
<contents>News2 Contents</contents>
<title>News2 Title</title>
<pubDate>February 1, 2012</pubDate>
</news>
<news>
<contents>News1 Contents</contents>
<title>News1 Title</title>
<pubDate>January 22, 2012</pubDate>
</news>
</theNews>
This is the code for my News Updater
<%# Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="NewsUpdater.aspx.vb" Inherits="NewsUpdater" %>
<%-- Add content controls here --%><asp:Content ID="Content1" runat="server"
contentplaceholderid="ContentPlaceHolder1">
<p>
</p>
<table align="center" style="width: 63%">
<tr>
<td align=center>
<div>
<h3>News Title</h3>
<asp:TextBox runat="server" ID="txtTitle" Width="308px"></asp:TextBox>
<br />
<h3>News Content</h3>
<asp:TextBox runat="server" ID="txtContents" TextMode="MultiLine" Height="119px" Width="513px"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Update News" />
</div></td>
</tr>
</table>
<p>
<br />
</p>
And this is the code behind the NewsUpdater button
Partial Class NewsUpdater
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim xmlFile As New System.Xml.XmlDocument()
xmlFile.Load("D:\My Documents\PresentableII\NewsContent.xml")
Dim theNewsTag As System.Xml.XmlElement = xmlFile.CreateElement("news")
Dim theTitleTag As System.Xml.XmlElement = xmlFile.CreateElement("title")
Dim theContentsTag As System.Xml.XmlElement = xmlFile.CreateElement("contents")
Dim theTitleText As System.Xml.XmlText = xmlFile.CreateTextNode(txtTitle.Text)
Dim theContentsText As System.Xml.XmlText = xmlFile.CreateTextNode(txtContents.Text)
theTitleTag.PrependChild(theTitleText)
theContentsTag.PrependChild(theContentsText)
theNewsTag.PrependChild(theTitleTag)
theNewsTag.PrependChild(theContentsTag)
xmlFile.DocumentElement.PrependChild(theNewsTag)
xmlFile.Save("D:\My Documents\PresentableII\NewsContent.xml")
Response.Redirect("NewsFrame.aspx")
End Sub
I want to add another button that has a function of remove or replace the last/latest entry to the xml.

So would this line do what you want?
xmlFile.DocumentElement.RemoveChild(xmlFile.DocumentElement.LastChild)
xmlFile.DocumentElement.AppendChild(your_replacement_element)

Related

Dynamic page creation from db at run time in asp.net

I'm making E-Commerce website. Under that I want to show particular product details. From query string I can do that but that is not seo friendly so I need to make product name in url(from db) instead of using querystring. I tried following code but it is not working for me.
Error - The resource could not be Found
Global.asax
<%# Application Language="VB" %>
<%# Import Namespace="System.Web.Optimization" %>
<%# Import Namespace="System.Web.Routing" %>
<script runat="server">
Sub Application_Start(sender As Object, e As EventArgs)
RouteConfig.RegisterRoutes(RouteTable.Routes)
BundleConfig.RegisterBundles(BundleTable.Bundles)
End Sub
Private Shared Sub RegisterRoutes(routes As RouteCollection)
routes.MapPageRoute("product-detail", "{product_name}.aspx", "product-detail.aspx")
End Sub
</script>
product-detail.aspx (Dynamic Page)
Private Sub product_detail_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim pageName As String = Me.Page.RouteData.Values("product_name").ToString()
End If
End Sub
shop.aspx (used listview control to display list of products)
<asp:ListView ID="products" runat="server" DataKeyNames="ID">
<ItemTemplate>
<asp:HyperLink ID="productID" runat="server" NavigateUrl='<%# Eval("product_name", "~/{0}") %>' CssClass="product-link">
<!--blocks-starts--><div class="blocks blocks-shop">
<asp:Image ID="readyStock" runat="server" ImageUrl="images/common/ready_stock_tag.png" Visible="false" CssClass="tag" />
<asp:Label ID="checkReadyStock" runat="server" Visible="false"></asp:Label>
<div class="block-img">
<img src='<%# Eval("image") %>' runat="server" id="proImg" />
</div>
<div class="block-content">
<span class="sku" style="font-size:0.6em !important">Item No. <asp:Label ID="skuID" runat="server" Text='<%# Eval("sku") %>'></asp:Label></span>
<h3>
<asp:Label ID="prodName" runat="server" Text='<%# Eval("product_name") %>'></asp:Label></h3>
<p><strong>
<asp:Label ID="priceRange" runat="server" Text='<%# Eval("price_range") %>'></asp:Label></strong></p>
</div>
</div><!--blocks-ends-->
</asp:HyperLink>
</ItemTemplate>
<LayoutTemplate>
<div id="itemPlaceholderContainer" runat="server" style="">
<div runat="server" id="itemPlaceholder" />
</div>
</LayoutTemplate>
</asp:ListView>
shop.aspx.vb
Private Sub shop_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Try
Dim str As String = "select * from products where status = 'active'"
Dim cmd As New MySqlCommand(str, con)
con.Open()
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
products.DataSource = dt
products.DataBind()
con.Close()
Catch ex As Exception
Response.Write(ex)
End Try
End If
End Sub

Shopping Cart Implemented in Visual Studio Express

i implemented a shopping cart found here: http://www.beansoftware.com/ASP.NET-Tutorials/Developing-Shopping-Cart.aspx
Whenever I run the project separately it would work perfect but when i move the .aspx classes and items into my project, i get these errors:
Type lstcart is not declared, It may be inaccessible due to its protection level. Place:Cart.aspx.vb line 22
Type CartItem is not defined. line 23 and 26
Handles Clause requires a WithEvents Variable defined in the containing type or one of its base types. line 38
"Lblmassage is not declared. It may be inaccessible due to its protection level. line : 41
The code of the program is found in the link i posted above, would anyone help me fixing my issue?
This is my cart.aspx.vb code:
Partial Class Cart
Inherits System.Web.UI.Page
Private Cart As SortedList
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Cart = GetCart()
If Not IsPostBack Then
Me.DisplayCart()
End If
End Sub
Private Function GetCart() As SortedList
If Session("Cart") Is Nothing Then
Session.Add("Cart", New SortedList)
End If
Return CType(Session("Cart"), SortedList)
End Function
Private Sub DisplayCart()
lstCart.Items.Clear()
Dim CartItem As CartItem
Dim CartEntry As DictionaryEntry
For Each CartEntry In Cart
CartItem = CType(CartEntry.Value, CartItem)
lstCart.Items.Add(CartItem.Display)
Next
End Sub
Protected Sub btnRemove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRemove.Click
If lstCart.SelectedIndex > -1 And Cart.Count > 0 Then
Cart.RemoveAt(lstCart.SelectedIndex)
Me.DisplayCart()
End If
End Sub
Protected Sub btnEmpty_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnEmpty.Click
Cart.Clear()
lstCart.Items.Clear()
lblMessage.Text = ""
End Sub
Protected Sub btnCheckOut_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCheckOut.Click
lblMessage.Text = "Please Wait Checking out..."
End Sub
End Class
This is my Cart.aspx:
<%# Page Title="Cart" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Cart.aspx.vb" Inherits="EliteHosting.Cart" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Shopping Cart</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<div style="font-size: xx-large; vertical-align: baseline; width: 614px; color: #ffffff;
direction: ltr; height: 112px; background-color: #660000; text-align: left; font-variant: normal">
<br />
My Web Shop</div><br /><br />
Your shopping cart:<br />
<table style="width: 500px" cellspacing="0"
cellpadding="0" border="0">
<tr>
<td style="width: 286px; height: 153px">
<asp:ListBox ID="lstCart" runat="server"
Width="267px" Height="135px">
</asp:ListBox>
</td>
<td style="height: 153px">
<asp:Button ID="btnRemove" runat="server"
Width="100px" Text="Remove Item" /><br /><br />
<asp:Button ID="btnEmpty" runat="server"
Width="100px" Text="Empty Cart" />
</td>
</tr>
</table>
<br />
<asp:Button ID="btnContinue" runat="server"
PostBackUrl="~/Order.aspx" Text="Continue Shopping" />
<asp:Button ID="btnCheckOut" runat="server" Text="Check Out" /><br />
<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</div>
</form>
</body>
</html>

ASP.net Syntax error in INSERT INTO statement - cmd.ExecuteNonQuery()

Currently doing a project and I am having a serious problem with some code. I keep getting the cmd.ExecuteNonQuery() and i have searched all over the internet to find the solution. I have inserted [] in certain catagories and still produces the same error.
All I am doing is creating a page where people can input data for certain catagories, in which once added, it will be updated to the access database. I had this working on an earlier version but ever since i added more characters, it has come with this error.
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="addcar.aspx.vb" Inherits="WebApplication1.addcar" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
<p>
<br />
CarName<asp:TextBox ID="tb_CarName" runat="server"></asp:TextBox>
</p>
<p>
<br />
Year<asp:TextBox ID="tb_Year" runat="server"></asp:TextBox>
</p>
<p>
<br />
EngineSize<asp:TextBox ID="tb_EngineSize" runat="server"></asp:TextBox>
</p>
<p>
<br />
BHP<asp:TextBox ID="tb_BHP" runat="server"></asp:TextBox>
</p>
<p>
<br />
Origin<asp:TextBox ID="tb_Origin" runat="server"></asp:TextBox>
</p>
<p>
<br />
Description<asp:TextBox ID="tb_Description" runat="server"></asp:TextBox>
</p>
<p>
<br />
Pictures<asp:TextBox ID="tb_Pictures" runat="server"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button" runat="server" Text="Add Car Details" />
</p>
</asp:Content>
Followed by the button code which is:
Imports System.Data.OleDb
Public Class addcar
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button_Click(sender As Object, e As EventArgs) Handles Button.Click
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("CarsConnectionString").ConnectionString)
Dim SqlString As String = "Insert into Table1(CarName,Year,EngineSize,BHP,Origin,Description,Pictures) Values (#f1,#f2,#f3,#f4,#f5,#f6,#f7)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_CarName.Text)
cmd.Parameters.AddWithValue("#f2", tb_Year.Text)
cmd.Parameters.AddWithValue("#f3", tb_EngineSize.Text)
cmd.Parameters.AddWithValue("#f4", tb_BHP.Text)
cmd.Parameters.AddWithValue("#f5", tb_Origin.Text)
cmd.Parameters.AddWithValue("#f6", tb_Description.Text)
cmd.Parameters.AddWithValue("#f7", tb_Pictures.Text)
oleDbConn.Open()
cmd.ExecuteNonQuery()
Response.Redirect("confirmation.aspx")
End Sub
End Class
Help? What am I doing wrong?
Error is as follows:
Syntax error in INSERT INTO statement.
Year is a reserved keyword in access / Jet.
You need to encapsulate it with square brackets.
Dim SqlString As String = "Insert into Table1(CarName, [Year],EngineSize,BHP,Origin,Description,Pictures) Values (#f1,#f2,#f3,#f4,#f5,#f6,#f7)"
You can check every reserved keyword in the jet engine here:
http://support.microsoft.com/kb/248738

Page_Load not update after click the button

I have a simple ASP.NET page:
sub Page_Load
//Get data form databse and show it
end sub
sud deletsome(Source As Object, e As EventArgs)
//delete one record when user click on submit button
end sub
When I click the button, the page reload, all the data have no change, I must re-enter the page again, the record I have delete disappear.
Can you show me why?
The full code here:
<%# Import Namespace="System.Data.OleDb" %>
<script runat="server">
sub Page_Load
dim dbconn,sql,dbcomm,dbread
dbconn=New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;data source=" & server.mappath("/data/test.accdb"))
dbconn.Open()
sql="SELECT * FROM [user]"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
customers.DataSource=dbread
customers.DataBind()
dbread.Close()
dbconn.Close()
end sub
sub deletesome(Source As Object, e As EventArgs)
dim dbconn,sql,dbcomm
dbconn=New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;data source=" & server.mappath("/data/test.accdb"))
dbconn.Open()
sql="DELETE FROM [user]WHERE id = #ID"
dbcomm=New OleDbCommand(sql,dbconn)
dbcomm.Parameters.AddWithValue("ID", tb1.Text)
dbcomm.ExecuteNonQuery()
end sub
</script>
<html>
<body>
<form runat="server">
<asp:TextBox id="tb1" runat="server" />
<asp:Button id="b1" Text="Submit" runat="server" OnClick="deletesome" />
<asp:Repeater id="customers" runat="server">
<HeaderTemplate>
<table border="1" width="100%">
<tr bgcolor="#b0c4de">
<th>ID</th>
<th>Address</th>
<th>City</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr bgcolor="#f0f0f0">
<td><%#Container.DataItem("id")%> </td>
<td><%#Container.DataItem("username")%> </td>
<td><%#Container.DataItem("userphone")%> </td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
<hr />
</body>
</html>
In asp page life cycle, page load happens before the button click (I know, it's kind of strange). The easiest work around is to place your code in the page "PreRender" event.
Use if(!IsPostBack) on page load.
You have not added the !IsPostBack condition in your page load event. When you click the button your page's load event is first called before the click event handler and it will reload the data again. That's the issue.
It should be like...
sub Page_Load
IF(!IsPostBack) ' This condition will be true when the page loads the first time
dim dbconn,sql,dbcomm,dbread
dbconn=New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;data source=" & server.mappath("/data/test.accdb"))
dbconn.Open()
sql="SELECT * FROM [user]"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
customers.DataSource=dbread
customers.DataBind()
dbread.Close()
dbconn.Close()
EndIf
end sub
try this
<%# Import Namespace="System.Data.OleDb" %>
<script runat="server">
sub Page_Load
If Page.IsPostBack = False Then
LoadData()
end sub
sub deletesome(Source As Object, e As EventArgs)
dim dbconn,sql,dbcomm
dbconn=New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;data source=" & server.mappath("/data/test.accdb"))
dbconn.Open()
sql="DELETE FROM [user]WHERE id = #ID"
dbcomm=New OleDbCommand(sql,dbconn)
dbcomm.Parameters.AddWithValue("ID", tb1.Text)
dbcomm.ExecuteNonQuery()
LoadData()
end sub
sub LoadData
dim dbconn,sql,dbcomm,dbread
dbconn=New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;data source=" & server.mappath("/data/test.accdb"))
dbconn.Open()
sql="SELECT * FROM [user]"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
customers.DataSource=dbread
customers.DataBind()
dbread.Close()
dbconn.Close()
end sub
</script>
<html>
<body>
<form runat="server">
<asp:TextBox id="tb1" runat="server" />
<asp:Button id="b1" Text="Submit" runat="server" OnClick="deletesome" />
<asp:Repeater id="customers" runat="server">
<HeaderTemplate>
<table border="1" width="100%">
<tr bgcolor="#b0c4de">
<th>ID</th>
<th>Address</th>
<th>City</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr bgcolor="#f0f0f0">
<td><%#Container.DataItem("id")%> </td>
<td><%#Container.DataItem("username")%> </td>
<td><%#Container.DataItem("userphone")%> </td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</form>
<hr />
</body>
</html>

Making changes to a pre-populated textbox

I have the following webform with textboxes that are pre-populated on page load:
<%# Page Title="" Language="VB" MasterPageFile="~/default.master" AutoEventWireup="true" CodeFile="admin.aspx.vb" Inherits="admin" Theme="G2M" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<form id="form1" Runat="Server">
<label>Username: </label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<label>Password: </label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<label>Product Type: </label>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br />
<label>SMTP Default Only: </label>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<br />
<label>Logo: </label>
<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
<br />
<asp:Button ID="submit" Text="Submit changes" runat="server" OnClick="SubmitChanges" />
</form>
</asp:Content>
And the codebehind is as follows:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim xmlDoc As New XmlDocument
xmlDoc.Load(Server.MapPath("~/XML_Config/Config.xml"))
Dim configValues As XMLParser = New XMLParser(xmlDoc) ''Instantiate the XMLParser
''Populate textboxes with XML data
TextBox1.Text = configValues.UserName
TextBox2.Text = configValues.Password
TextBox3.Text = configValues.ProductType
TextBox4.Text = configValues.SMTPDefaultOnly
TextBox5.Text = configValues.Logo
End Sub
Public Sub SubmitChanges(ByVal sender As Object, ByVal e As System.EventArgs)
Dim xmlDoc As New XmlDocument
xmlDoc.Load(Server.MapPath("~/XML_Config/Config.xml"))
Dim configValues As XMLParser = New XMLParser(xmlDoc) ''Instantiate the XMLParser
configValues.SMTPDefaultOnly = TextBox4.Text
End Sub
All I'm trying to do is make the values editable so when the form is presented to the user, they can change the values and submit them back to the file. My problem is that when the SubmitChanges function is called, even though I change the value of the textbox, it is still the same. How do I pass a new value, typed into thetextbox, to the function?
Enclose your setter in If Not ispostback in that page load. It's overwriting the boxes.

Resources