This tutorial will show you how to share code between pages using ASP.NET 2.0 and VB.NET.
Although you can place code inside each page within your site (using the inline or code-behind separation models described in the previous section), there are times when you will want to share code across several pages in your site. It would be inefficient and difficult to maintain this code by copying it to every page that needs it. Fortunately, ASP.NET provides several convenient ways to make code accessible to all pages in an application.
The following example demonstrates an App_Code directory partitioned to contain files in both the VB and C# languages.
Using default namespace in the example.
First you need to build a CustomClassCsharp class in the folder Subdirectory.the code as following:
|
using System;
/// <summary>
/// CustomClassCsharp summary
/// </summary>
public class CustomClassCsharp
{
public String GetMessage(String input)
{
return "Hello from C# " + input;
}
}
|
Secondly, build a CustomClass the code as following:
|
Imports Microsoft.VisualBasic
Public Class CustomClass
Public Function GetMessage(ByVal name As String) As String
Return "Hello " & name
End Function
End Class
|
Thirdly,build a web.config file Site.master.the code as following:
|
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation>
<codeSubDirectories>
<add directoryName="Subdirectory"/>
</codeSubDirectories>
</compilation>
</system.web>
</configuration>
|
The front end SharingCodeBetweenPagesCsharp.aspx page looks something like this:
|
<div align="center">
<b>Enter Your Name:</b>
<asp:TextBox ID="TextBox1" Runat="server"/>
<asp:Button ID="Button1" Text="Click Me" Runat="server" OnClick="Button1_Click"/>
<br />
<br />
<asp:Label ID="Label1" Runat="server" />
<br />
<asp:Label ID="Label2" Runat="server" />
</div>
|
The flow for the code behind page is as follows
|
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim c As New CustomClass
Label1.Text = c.GetMessage(TextBox1.Text)
Dim c2 As New CustomClassCsharp
Label2.Text = c2.GetMessage(TextBox1.Text)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class
|
This tutorial is provided in part by Mega Solutions Mega Solutions Inc.
Visit http://www.megasolutions.net for more ASP.NET Tutorials and Resources
This tutorial will show you how to store data with Hashtable using ASP.NET 2.0 and VB.NET.
At first, you need to import the namespace from System.Collections.
The System.Collections namespace contains classe Hashtable which represents a collection of key/value pairs that are organized based on the hash code of the key.
| imports System.Collections |
In order to run the example, we will use the btn_get_Click to trigger the task. The code as following:
|
Protected Sub btn_get_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_get.Click
Dim key As Integer
Dim name As String = String.Empty
Dim str As String = String.Empty
Dim hashtable As Hashtable = New Hashtable()
key = 1
name = "Jake"
Hashtable.Add(key, name)
key = 2
name = "peter"
Hashtable.Add(key, name)
key = 3
name = "lily"
Hashtable.Add(key, name)
For Each de As DictionaryEntry In hashtable
str = str + "key=" + CType(de.Key, String) + " " + " value=" + de.Value.ToString() + "<br>"
Next de
Me.Label1.Text = str
End Sub
|
The front end StoreDataWithHashtableVB.aspx page looks something like this:
|
<div align="left" style='text-align: center'>
<table>
<tr>
<td colspan="2" style='width: 402px'>
<asp:Label ID="Label1" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2" style='height: 26px; width: 402px;'>
<asp:Button ID="btn_get" runat="server" Text="Get data from hashtable" OnClick="btn_get_Click"/></td>
</tr>
</table>
</div>
|
The flow for the code behind page is as follows
|
Imports System.Collections
Partial Class _Default
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 btn_get_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_get.Click
Dim key As Integer
Dim name As String = String.Empty
Dim str As String = String.Empty
Dim hashtable As Hashtable = New Hashtable()
key = 1
name = "Jake"
Hashtable.Add(key, name)
key = 2
name = "peter"
Hashtable.Add(key, name)
key = 3
name = "lily"
Hashtable.Add(key, name)
For Each de As DictionaryEntry In hashtable
str = str + "key=" + CType(de.Key, String) + " " + " value=" + de.Value.ToString() + "<br>"
Next de
Me.Label1.Text = str
End Sub
End Class
|
This tutorial will show you how to cut string using ASP.NET 2.0 and VB.NET 2005.
The tutorial use default namespace. The sampe will show you how to intercept the character string and restrict the character length. Moreover, it will automatically turn to the newline.
In order to run the example, we will use the btn_cut_Click to trigger the task.the code as following:
Protected Sub btn_cut_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_cut.Click Dim s As String = "" Dim str As String = String.Empty str = txtInputString.Text.Trim() Dim len As Integer = 0 If txt_length.Text.Equals("") = False Then len = Int32.Parse(txt_length.Text.Trim()) End If For i As Integer = 0 To str.Length Dim r As Integer = i Mod len Dim last As Integer = (str.Length / len) * len If i <> 0 And i <= last Then If r = 0 Then s += str.Substring(i - len, len) + "<br>" End If ElseIf i > last Then s += str.Substring(i - 1) Exit For End If next Me.lblMessage.Text = s End Sub |
The front end CutStringVB.aspx page looks something like this:
<div align="left" style='text-align: center'> <table> <tr> <td colspan="2" style='width: 200px'> Input String :</td> <td colspan="1" style='width: 17px'> <asp:TextBox ID="txtInputString" runat="server"></asp:TextBox></td> </tr> <tr> <td colspan="2" style='height: 26px'> Length:</td> <td colspan="1" style='width: 17px'> <asp:TextBox ID="txt_length" runat="server"></asp:TextBox></td> </tr> <tr> <td colspan="3" style='height: 26px'> <asp:Button ID="btn_cut" runat="server" Text="Cut String" OnClick="btn_cut_Click"/></td> </tr> <tr> <td colspan="3" style='height: 26px'> <asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label></td> </tr> </table> </div> |
The flow for the code behind page is as follows
Partial Class _Default Inherits System.Web.UI.Page
Protected Sub btn_cut_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_cut.Click Dim s As String = "" Dim str As String = String.Empty str = txtInputString.Text.Trim() Dim len As Integer = 0 If txt_length.Text.Equals("") = False Then len = Int32.Parse(txt_length.Text.Trim()) End If For i As Integer = 0 To str.Length Dim r As Integer = i Mod len Dim last As Integer = (str.Length / len) * len If i <> 0 And i <= last Then If r = 0 Then s += str.Substring(i - len, len) + "<br>" End If ElseIf i > last Then s += str.Substring(i - 1) Exit For End If next Me.lblMessage.Text = s End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub End Class
|
This tutorial is provided in part by Mega Solutions Mega Solutions Inc.
Visit http://www.megasolutions.net for more ASP.NET Tutorials and Resources
This tutorial will show you how to use SiteMapPath with the Menu control to build up site navigation menu by using ASP.NET 2.0 and VB.NET.
The controls of Menu, SiteMapPath and SiteMapDataSource can generate navigation UI based on navigation data. This data can be stored in XML files, or it can be stored using the provider-based storage capabilities of the Site Navigation feature. This samples demonstrate using the different controls in conjunction with the Site Navigation feature.
At first, you will need to create a file Web.sitemap. The code as following:
<?xml version="1.0" encoding="utf-8" ?> <siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" > <siteMapNode title="Home" url="~/SiteMapPathTreeViewCsharp.aspx" description="Home Page" > <siteMapNode title="Section One" url="~/sectionone.aspx" description="Section One"> <siteMapNode title="First Page" url="~/sectionone/firstpage.aspx" description="Section One - First Page"/> <siteMapNode title="Second Page" url="~/sectionone/secondpage.aspx" description="Section One - Second Page"/> </siteMapNode> <siteMapNode title="Section Two" url="~/sectiontwo.aspx" description="Section Two"> <siteMapNode title="First Page" url="~/sectiontwo/firstpage.aspx" description="Section Two - First Page"/> <siteMapNode title="Second Page" url="~/sectiontwo/secondpage.aspx" description="Section Two - Second Page"/> </siteMapNode> </siteMapNode> </siteMap>
|
Secondly, please build a MasterPage file Site.master. The code as following:
<table cellspacing="0" cellpadding="5" border="0" height="80%"> <tr> <td style='width: 100px' valign='top'> <asp:treeview ID="TreeView1" ForeColor="White" DataSourceId="SiteMapDataSource1" NodeIndent="0" NodeStyle-ChildNodesPadding="10" runat="server"> <LevelStyles> <asp:TreeNodeStyle Font-Bold="true"/> <asp:TreeNodeStyle /> <asp:TreeNodeStyle Font-Size="x-small"/> </LevelStyles> <nodestyle forecolor="White" HorizontalPadding="5"/> <SelectedNodeStyle backcolor="lightblue" forecolor="blue" /> <HoverNodeStyle Font-UnderLine="true" /> </asp:treeview> </td> <td style='background-color: white;padding-left:25;padding-top:15' colspan='2' valign='top'> <b>Current Page: </b> <asp:sitemappath id="SiteMapPath1" runat="server" /> <br/> <br /> <asp:contentplaceholder id="MainBody" runat="server" /> </td> </tr> </table> <asp:sitemapdatasource id="SiteMapDataSource1" runat="server" /> |
The front end SiteMapPathMenuNavigationVB.aspx page looks something like this: <%@ Page Language="VB" MasterPageFile="~/Site.master"%> <asp:Content ID="Content1" ContentPlaceHolderID="MainBody" Runat="Server"> This is the home page </asp:Content> |
This tutorial will show you how to use URL mapping technology in ASP.NET 2.0 and VB.NET.
The URL mapping feature uses configuration information stored in web.config to remap incoming requests to a different URL. The remapping occurs prior to any other processing for the inbound request. Although the sample below demonstrates remapping a page request, any arbitrary file type can have its request remapped to a different URL.
At first you need to build a sitemap file Web.sitemap. The code as following:
<?xml version="1.0" encoding="utf-8" ?> <siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0"> <siteMapNode url="~/UrlMappingVB.aspx" title="Home Page" description="This is the home page" > <siteMapNode url="~/Category.aspx" title="Categories" description="Information Categories" > <siteMapNode title="News" description="News" url="~/News.aspx" /> <siteMapNode title="Games" description="Games" url="~/Games.aspx" /> <siteMapNode title="Health" description="Health" url="~/Health.aspx" /> </siteMapNode> </siteMapNode> </siteMap>
|
Secondly, please build a web.config file. The code as following:
<?xml version="1.0" ?> <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <system.web> <urlMappings enabled="true"> <add url="~/News.aspx" mappedUrl="~/UrlMappingVB.aspx?category=news" /> <add url="~/Category.aspx" mappedUrl="~/UrlMappingVB.aspx?category=default" /> <add url="~/Games.aspx" mappedUrl="~/UrlMappingVB.aspx?category=games" /> <add url="~/Health.aspx" mappedUrl="~/UrlMappingVB.aspx?category=health" /> </urlMappings> </system.web> </configuration>
|
The front end SiteMapPathTreeViewNavigationVB.aspx page looks something like this: <table> <tr> <td><asp:SiteMapDataSource Runat=server ID="SiteMapDataSource1" /> <br /></td> </tr> <tr> <td> <asp:Label Runat=server Text="TreeView" id="Label3" ForeColor="#ff3366" /> <asp:TreeView ID="TreeView1" DataSourceID="SiteMapDataSource1" Runat=Server /> </td> </tr> <tr> <td> The current virtual path for the request is:<b> <% Response.Write(Request.Path)%></b>. <br /> The value of the category querystring variable is:<b> <% Response.Write(Server.HtmlEncode(Request.QueryString("category")))%></b>. <br /> However, the original path that was requested before it was remapped is:<b> <% Response.Write(Request.RawUrl)%></b>. </td> </tr> </table>
|
This tutorial will show you how to navigate XML information items in ASP.NET 2.0 using C#.
First, import the namespace of System.XML and System.XML.XPath
The System.Xml.XPath namespace contains the classes that define a cursor model for navigating and editing XML information items as instances of the XPath 2.0 Data Model. In this sample, we will use the classes of XPathDocument, XPathNavigator, XPathExpression and XPathNodeIterator under this namespace .
using System.Xml; using System.Xml.XPath; |
The Button1_Click event is to perform the navgating XML infomration items fuction. The results will be displayed in the textbox. There are 4 classes we applied.
XPathDocument: Provides a fast, read-only, in-memory representation of an XML document using the XPath data model.
XPathNavigator: Provides a cursor model for navigating XML data.
XPathExpression: Provides a typed class that represents a compiled XPath expression.
XPathNodeIterator: Provides an iterator over a selected set of nodes.
XPathDocument doc = new XPathDocument(Server.MapPath("Demo.xml")); XPathNavigator nav = doc.CreateNavigator();
XPathExpression xpathExpress = nav.Compile("//bk:Book[position()"+this.ddownlist.SelectedValue.Trim()+this.txtNum.Text.Trim()+"]"); //use AddNamespace XmlNamespaceManager xmlManager = new XmlNamespaceManager(nav.NameTable); xmlManager.AddNamespace("bk", "http://myserver/myschemas/Books"); xpathExpress.SetContext(xmlManager);
XPathNodeIterator xIterator = nav.Select(xpathExpress); this.TextBox1.Text = ""; this.TextBox1.ForeColor = System.Drawing.Color.Empty; while (xIterator.MoveNext()) this.TextBox1.Text = this.TextBox1.Text + "\r\n" + xIterator.Current.Value;
if (xIterator.Count.Equals(0)) { this.TextBox1.Text = "There is no xml data in the condition."; this.TextBox1.ForeColor = System.Drawing.Color.Red; } xmlManager = null; nav = null; doc = null; |
The contents of Demo.xml
<?xml version='1.0' encoding='utf-8'?> <bk:Books xmlns:bk='http://myserver/myschemas/Books'> <bk:Book> <bk:Title>Just XML</bk:Title> </bk:Book> <bk:Book> <bk:Title>Professional XML</bk:Title> </bk:Book> <bk:Book> <bk:Title>XML Step by Step</bk:Title> </bk:Book> <bk:Book> <bk:Title>XML By Example</bk:Title> </bk:Book> </bk:Books> |
The front end Default.aspx page looks something like this:
<body> <form id="form1" runat="server"> <div> <fieldset><legend>Select xml data with XPath</legend> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" Font-Size="Smaller" ForeColor="#333333" GridLines="None" RowHeaderColumn="Title" Width="205px"> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <Columns> <asp:BoundField DataField="Title" HeaderText="Title" /> </Columns> <RowStyle BackColor="#EFF3FB" /> <EditRowStyle BackColor="#2461BF" /> <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView> <br /> <asp:Label ID="Label1" runat="server" Text="Select Item Position:"></asp:Label> <asp:DropDownList ID="ddownlist" runat="server"> <asp:ListItem><</asp:ListItem> <asp:ListItem><=</asp:ListItem> <asp:ListItem>></asp:ListItem> <asp:ListItem>>=</asp:ListItem> </asp:DropDownList> <asp:TextBox ID="txtNum" runat="server" Width="57px">2</asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtNum" ErrorMessage="Please input integer number."></asp:RequiredFieldValidator><br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search" /><br /> <asp:TextBox ID="TextBox1" runat="server" Height="88px" TextMode="MultiLine" Width="237px"></asp:TextBox> </fieldset> </div> </form> </body> |
The flow for the code behind page is as follows.
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;
using System.Xml; using System.Xml.XPath;
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DataSet myDs = new DataSet(); myDs.ReadXml(Server.MapPath("Demo.xml")); this.GridView1.DataSource = myDs; this.GridView1.DataBind(); } protected void Button1_Click(object sender, EventArgs e) { XPathDocument doc = new XPathDocument(Server.MapPath("Demo.xml")); XPathNavigator nav = doc.CreateNavigator();
XPathExpression xpathExpress = nav.Compile("//bk:Book[position()"+this.ddownlist.SelectedValue.Trim()+this.txtNum.Text.Trim()+"]"); //use AddNamespace XmlNamespaceManager xmlManager = new XmlNamespaceManager(nav.NameTable); xmlManager.AddNamespace("bk", "http://myserver/myschemas/Books"); xpathExpress.SetContext(xmlManager);
XPathNodeIterator xIterator = nav.Select(xpathExpress); this.TextBox1.Text = ""; this.TextBox1.ForeColor = System.Drawing.Color.Empty; while (xIterator.MoveNext()) this.TextBox1.Text = this.TextBox1.Text + "\r\n" + xIterator.Current.Value;
if (xIterator.Count.Equals(0)) { this.TextBox1.Text = "There is no xml data in the condition."; this.TextBox1.ForeColor = System.Drawing.Color.Red; } xmlManager = null; nav = null; doc = null; } }
|
RSS Feed is very popular in Internet. This tutorial will show you how to create a RSS Reader using ASP.NET 2.0 and VB.NET.
At first, import the namespace of System.Net, System.IO, and System.Xml
Imports System.Net Imports System.IO Imports System.Xml
|
In this sample, we created a simple function to process the RSS feed from a sample URL. This function define a string of rssURL as its parameter. This string contains the RSS's URL. It will use the value of rssURL to create a WebRequest.
WebRequest is the abstract base class for the .NET Framework's request/response model for accessing data from the Internet. An application that uses the request/response model can request data from the Internet in a protocol-agnostic manner, in which the application works with instances of the WebRequest class while protocol-specific descendant classes carry out the details of the request.
Requests are sent from an application to a particular URI, such as a Web page on a server. The URI determines the proper descendant class to create from a list of WebRequest descendants registered for the application. WebRequest descendants are typically registered to handle a specific protocol, such as HTTP or FTP, but can be registered to handle a request to a specific server or path on a server.
The response to this request will be put into WebResponse object. The WebResponse class is the abstract base class from which protocol-specific response classes are derived. Applications can participate in request and response transactions in a protocol-agnostic manner using instances of the WebResponse class while protocol-specific classes derived from WebResponse carry out the details of the request. Client applications do not create WebResponse objects directly; they are created by calling the GetResponse method on a WebRequest instance.
After then, the WebResponse object will be used to create a stream to get the XML data. Stream is the abstract base class of all streams. A stream is an abstraction of a sequence of bytes, such as a file, an input/output device, an inter-process communication pipe, or a TCP/IP socket. The Stream class and its derived classes provide a generic view of these different types of input and output, isolating the programmer from the specific details of the operating system and the underlying devices. The we used a XmlDocument to store the stream data. XmlDocument manipulating the data of XML, finally read the RSS contents from Feed.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim rssURL As String = "http://www.codeguru.com/icom_includes/feeds/codeguru/rss-all.xml" Response.Write("<font size=5><b>Site: " + rssURL + "</b></font><Br />") ProcessRSSItem(rssURL) Response.Write("<hr />") rssURL = "http://www.developer.com/icom_includes/feeds/special/dev-5.xml" Response.Write("<font size=5><b>Site: " + rssURL + "</b></font><Br />") Call ProcessRSSItem(rssURL) End Sub Private Sub ProcessRSSItem(ByVal rssURL As String)
Dim myRequest As WebRequest = System.Net.WebRequest.Create(rssURL) Dim myResponse As WebResponse = myRequest.GetResponse() Dim rssStream As Stream = myResponse.GetResponseStream() Dim rssDoc As New XmlDocument() rssDoc.Load(rssStream) Dim rssItems As XmlNodeList = rssDoc.SelectNodes("rss/channel/item") Dim title As String = "" Dim link As String = "" Dim description As String = "" Dim i As Integer For i = 0 To rssItems.Count - 1 Dim rssDetail As XmlNode rssDetail = rssItems.Item(i).SelectSingleNode("title") If rssDetail.Equals(Nothing) = False Then title = rssDetail.InnerText Else title = "" End If rssDetail = rssItems.Item(i).SelectSingleNode("link") If rssDetail.Equals(Nothing) = False Then link = rssDetail.InnerText Else link = "" End If
rssDetail = rssItems.Item(i).SelectSingleNode("description") If rssDetail.Equals(Nothing) = False Then description = rssDetail.InnerText Else description = "" End If Response.Write("<p><b><a href='" + link + "' target='new'>" + title + "</a></b><br/>") Response.Write(description + "</p>") Next End Sub End Class |
The front end Default.aspx page looks something like this:
<html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>RSS</title> </head> <body> <form id="form1" runat="server"> <div> <fieldset style='height: 383px'> <legend><strong>RSS</strong></legend><br /> </fieldset> </div> </form> </body> </html> |
The flow for the code behind page is as follows.
Imports System.Net Imports System.IO Imports System.Xml Partial Class _Default Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim rssURL As String = "http://www.codeguru.com/icom_includes/feeds/codeguru/rss-all.xml" Response.Write("<font size=5><b>Site: " + rssURL + "</b></font><Br />") ProcessRSSItem(rssURL) Response.Write("<hr />") rssURL = "http://www.developer.com/icom_includes/feeds/special/dev-5.xml" Response.Write("<font size=5><b>Site: " + rssURL + "</b></font><Br />") Call ProcessRSSItem(rssURL) End Sub Private Sub ProcessRSSItem(ByVal rssURL As String)
Dim myRequest As WebRequest = System.Net.WebRequest.Create(rssURL) Dim myResponse As WebResponse = myRequest.GetResponse() Dim rssStream As Stream = myResponse.GetResponseStream() Dim rssDoc As New XmlDocument() rssDoc.Load(rssStream) Dim rssItems As XmlNodeList = rssDoc.SelectNodes("rss/channel/item") Dim title As String = "" Dim link As String = "" Dim description As String = "" Dim i As Integer For i = 0 To rssItems.Count - 1 Dim rssDetail As XmlNode rssDetail = rssItems.Item(i).SelectSingleNode("title") If rssDetail.Equals(Nothing) = False Then title = rssDetail.InnerText Else title = "" End If rssDetail = rssItems.Item(i).SelectSingleNode("link") If rssDetail.Equals(Nothing) = False Then link = rssDetail.InnerText Else link = "" End If
rssDetail = rssItems.Item(i).SelectSingleNode("description") If rssDetail.Equals(Nothing) = False Then description = rssDetail.InnerText Else description = "" End If Response.Write("<p><b><a href='" + link + "' target='new'>" + title + "</a></b><br/>") Response.Write(description + "</p>") Next End Sub End Class |
This tutorial will show you how to calculate average of data from XML using ASP.NET 2.0 and VB.
This tutorial will show you how to calculate average of data from XML using ASP.NET 2.0 and C#. The System.Xml.XPath namespace contains the classes that define a cursor model for navigating and editing XML information items as instances of the XPath 2.0 Data Model. XPath expressions as a string, or a compiled XPathExpression that return a W3C XPath type of boolean (System.Boolean), number (System.Double), string (System.String), or node set (System.Xml.XPath.XPathNodeIterator), can be passed to the Evaluate method. The Evaluate method takes the expression, evaluates it, and returns a typed result. This method could be used in a mathematical user defined method. For example, the following code calculates the total price of all item elements and div number of book in the current selection.
XPathNavigator class Provides a cursor model for navigating and editing XML data.
XPathDocument class Provides a fast, read-only cache for XML document processing using XSLT.
XPathNodeIterator class Provides an iterator over a selected set of nodes.
Imports System.Xml Imports System.Xml.XPath Imports System.Data.SqlClient |
The following code of Button1_Click uses the Evaluate method with the average function.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click docNav = New XPathDocument(Server.MapPath("Books.xml")) nav = docNav.CreateNavigator() strExpression = "sum(/bookstore/book/price) div count(/bookstore/book/price)" Label1.Text = nav.Evaluate(strExpression).ToString() End Sub |
The front end AverageXmlDataCsharp.aspx page looks something like this:
<div> <br /> <table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#5482fc"> <tr> <td height="50" align="center" class="lgHeader1"> How to Average xmldata using ASP.NET 2.0 and C#</td> </tr> </table> <div align="center"> <fieldset style='width: 589px'> <legend>Average Price</legend> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None"> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <Columns> <asp:BoundField DataField="title" HeaderText="Title" /> <asp:BoundField DataField="author" HeaderText="Author" /> <asp:BoundField DataField="price" HeaderText="Price" /> </Columns> <RowStyle BackColor="#EFF3FB" /> <EditRowStyle BackColor="#2461BF" /> <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Average price" /> <asp:Label ID="Label1" runat="server" Text="Show averagedata from xml document:"></asp:Label></fieldset> </div> |
code behind page is as follows.
Imports System.Data Imports System.Data.SqlClient Imports System.Xml Imports System.Xml.XPath
Partial Class _Default Inherits System.Web.UI.Page
Dim nav As XPathNavigator Dim docNav As XPathDocument Dim nodeIter As XPathNodeIterator Dim strExpression As String Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim myDs As DataSet = New DataSet() myDs.ReadXml(Server.MapPath("Books.xml"))
Me.GridView1.DataSource = myDs.Tables("book").DefaultView Me.GridView1.DataBind() myDs.Clear() End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click docNav = New XPathDocument(Server.MapPath("Books.xml")) nav = docNav.CreateNavigator() strExpression = "sum(/bookstore/book/price) div count(/bookstore/book/price)" Label1.Text = nav.Evaluate(strExpression).ToString() End Sub End Class
|
Filed under: ASP.NET, VB.NET, XPath, XML information items, XML, XPathExpression, XPathDocument, XML items, XPathNodeIterator, SUM, XPathNavigator, Div
This tutorial will show you how to send a simple email message using ASP.NET 2.0 and VB.NET
Sending a email using ASP.NET 2.0 and VB.NET is actually very simple.
First, you will need to import the
System.Net.Mail namespace.
The
System.Net.Mail namespace contains the
SmtpClient and
MailMessage Classes that we need in order to send the email.
We use the btnSubmit_Click event to do the work.
We then call the emailClient.Send to send the message using the variables from our ASP.NET coded page.
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Try Dim message As New MailMessage(txtTo.Text, txtFrom.Text, txtSubject.Text, txtBody.Text) Dim emailClient As New SmtpClient(txtSMTPServer.Text) emailClient.Send(message) litStatus.Text = "Message Sent" Catch ex As Exception litStatus.Text = ex.ToString() End Try End Sub |
The front end .aspx page looks something like this:
<table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#cccccc"> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> To</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtTo" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> From</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtFrom" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1"> SMTP Server</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtSMTPServer" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> Subject</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtSubject" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> Body</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtBody" runat="server" Columns="40" TextMode="MultiLine"></asp:TextBox></td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1">Action</td> <td bgcolor="#FFFFFF"><asp:Button ID="btnSubmit" runat="server" Text="Send Email" OnClick="btnSubmit_Click" /></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1">Status</td> <td bgcolor="#FFFFFF" class="basix"><asp:Literal ID="litStatus" runat="server"></asp:Literal></td> </tr> </table> |
The flow for the code behind page is as follows.
Imports System.Net.Mail Partial Class _Default Inherits System.Web.UI.Page Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Try Dim message As New MailMessage(txtTo.Text, txtFrom.Text, txtSubject.Text, txtBody.Text) Dim emailClient As New SmtpClient(txtSMTPServer.Text) emailClient.Send(message) litStatus.Text = "Message Sent" Catch ex As Exception litStatus.Text = ex.ToString() End Try End Sub End Class
|
This tutorial will show you how to send a simple email message with an attachment using ASP.NET 2.0 and VB.NET
Sending a email with an attachment using ASP.NET 2.0 and VB.NET is actually very simple.
First, you will need to import the
System.Net.Mail namespace.
The
System.Net.Mail namespace contains the
SmtpClient and
MailMessage Classes that we need in order to send the email and the message attachment.
We use the btnSubmit_Click event to do the work.
We then call the emailClient.Send to send the message using the variables from our ASP.NET coded page.
The txtAttachmentPath.Text Texbox provides the path to the file to attach to the email message.
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Try Dim SendFrom As MailAddress = New MailAddress(txtFrom.Text) Dim SendTo As MailAddress = New MailAddress(txtTo.Text) Dim MyMessage As MailMessage = New MailMessage(SendFrom, SendTo) MyMessage.Subject = txtSubject.Text MyMessage.Body = txtBody.Text Dim attachFile As New Attachment(txtAttachmentPath.Text) MyMessage.Attachments.Add(attachFile) Dim emailClient As New SmtpClient(txtSMTPServer.Text) emailClient.Send(MyMessage) litStatus.Text = "Message Sent" Catch ex As Exception litStatus.Text = ex.ToString() End Try End Sub |
The front end .aspx page looks something like this:
<table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#cccccc"> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> To</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtTo" runat="server" Columns="50"></asp:TextBox> </td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> From</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtFrom" runat="server" Columns="50"></asp:TextBox> </td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1"> SMTP Server</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtSMTPServer" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> Subject</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtSubject" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1"> Attachment</td> <td bgcolor="#FFFFFF"> <asp:TextBox ID="txtAttachmentPath" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> Body</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtBody" runat="server" Columns="40" TextMode="MultiLine"></asp:TextBox></td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1">Action</td> <td bgcolor="#FFFFFF"><asp:Button ID="btnSubmit" runat="server" Text="Send Email" OnClick="btnSubmit_Click" /></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1">Status</td> <td bgcolor="#FFFFFF" class="basix"><asp:Literal ID="litStatus" runat="server"></asp:Literal></td> </tr> </table> |
The flow for the code behind page is as follows.
Imports System.Net.Mail Partial Class _Default Inherits System.Web.UI.Page Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Try Dim SendFrom As MailAddress = New MailAddress(txtFrom.Text) Dim SendTo As MailAddress = New MailAddress(txtTo.Text) Dim MyMessage As MailMessage = New MailMessage(SendFrom, SendTo) MyMessage.Subject = txtSubject.Text MyMessage.Body = txtBody.Text Dim attachFile As New Attachment(txtAttachmentPath.Text) MyMessage.Attachments.Add(attachFile) Dim emailClient As New SmtpClient(txtSMTPServer.Text) emailClient.Send(MyMessage) litStatus.Text = "Message Sent" Catch ex As Exception litStatus.Text = ex.ToString() End Try End Sub End Class |
This tutorial will show you how to send a simple email message with CCs and BCCs using ASP.NET 2.0 and VB.NET
Sending a email with CCs and BCCs using ASP.NET 2.0 and VB.NET is actually very simple.
First, you will need to import the
System.Net.Mail namespace.
The
System.Net.Mail namespace contains the
SmtpClient and
MailMessage Classes that we need in order to send the email and specify the CCs.
We use the btnSubmit_Click event to do the work.
We then call the emailClient.Send to send the message using the variables from our ASP.NET coded page. We use the CC and Bcc methods to add the emails we would like to CC to.
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Try Dim SendFrom As MailAddress = New MailAddress(txtFrom.Text) Dim SendTo As MailAddress = New MailAddress(txtTo.Text) Dim SendCC As MailAddress = New MailAddress(txtCC.Text) Dim SendBCC As MailAddress = New MailAddress(txtBCC.Text) Dim MyMessage As MailMessage = New MailMessage(SendFrom, SendTo) MyMessage.CC.Add(SendCC) MyMessage.Bcc.Add(SendBCC) MyMessage.Subject = txtSubject.Text MyMessage.Body = txtBody.Text Dim emailClient As New SmtpClient(txtSMTPServer.Text) emailClient.Send(MyMessage) litStatus.Text = "Message Sent" Catch ex As Exception litStatus.Text = ex.ToString() End Try End Sub |
The front end .aspx page looks something like this:
<table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#cccccc"> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> To</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtTo" runat="server" Columns="50"></asp:TextBox> </td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> From</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtFrom" runat="server" Columns="50"></asp:TextBox> </td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1"> CC</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtCC" runat="server" Columns="50"></asp:TextBox> </td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1"> BCC</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtBCC" runat="server" Columns="50"></asp:TextBox> </td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1"> SMTP Server</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtSMTPServer" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> Subject</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtSubject" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> Body</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtBody" runat="server" Columns="40" TextMode="MultiLine"></asp:TextBox></td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1">Action</td> <td bgcolor="#FFFFFF"><asp:Button ID="btnSubmit" runat="server" Text="Send Email" OnClick="btnSubmit_Click" /></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1">Status</td> <td bgcolor="#FFFFFF" class="basix"><asp:Literal ID="litStatus" runat="server"></asp:Literal></td> </tr> </table> |
The flow for the code behind page is as follows.
Imports System.Net.Mail Partial Class _Default Inherits System.Web.UI.Page Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Try Dim SendFrom As MailAddress = New MailAddress(txtFrom.Text) Dim SendTo As MailAddress = New MailAddress(txtTo.Text) Dim SendCC As MailAddress = New MailAddress(txtCC.Text) Dim SendBCC As MailAddress = New MailAddress(txtBCC.Text) Dim MyMessage As MailMessage = New MailMessage(SendFrom, SendTo) MyMessage.CC.Add(SendCC) MyMessage.Bcc.Add(SendBCC) MyMessage.Subject = txtSubject.Text MyMessage.Body = txtBody.Text Dim emailClient As New SmtpClient(txtSMTPServer.Text) emailClient.Send(MyMessage) litStatus.Text = "Message Sent" Catch ex As Exception litStatus.Text = ex.ToString() End Try End Sub End Class |
This tutorial will show you how to send a simple email message with priorities using ASP.NET 2.0 and VB.NET
Sending a email with Priorities using ASP.NET 2.0 and VB.NET is actually very simple.
First, you will need to import the
System.Net.Mail namespace.
The
System.Net.Mail namespace contains the
SmtpClient and
MailMessage Classes that we need in order to send the email and specify the Priority.
We use the btnSubmit_Click event to do the work.
We then call the emailClient.Send to send the message using the variables from our ASP.NET coded page. We then use a switch statement to determine the desired level of priority and set the Priority property of our MailMessage object accordingly.
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Try Dim SendFrom As MailAddress = New MailAddress(txtFrom.Text) Dim SendTo As MailAddress = New MailAddress(txtTo.Text) Dim MyMessage As MailMessage = New MailMessage(SendFrom, SendTo) MyMessage.Subject = txtSubject.Text MyMessage.Body = txtBody.Text Select Case ddPriority.SelectedValue Case "Low" MyMessage.Priority = MailPriority.Low Case "Normal" MyMessage.Priority = MailPriority.Normal Case "High" MyMessage.Priority = MailPriority.High End Select Dim emailClient As New SmtpClient(txtSMTPServer.Text) emailClient.Send(MyMessage) litStatus.Text = "Message Sent" Catch ex As Exception litStatus.Text = ex.ToString() End Try End Sub |
The front end .aspx page looks something like this:
<table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#5482fc"> <tr> <td height="50" align="center" class="lgHeader1">How to set Email Priority using ASP.NET 2.0 and C#</td> </tr> </table> <br /> <table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#cccccc"> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> To</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtTo" runat="server" Columns="50"></asp:TextBox> </td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> From</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtFrom" runat="server" Columns="50"></asp:TextBox> </td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1"> SMTP Server</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtSMTPServer" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> Subject</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtSubject" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1"> Priority</td> <td bgcolor="#ffffff"> <asp:DropDownList ID="ddPriority" runat="server"> <asp:ListItem>Low</asp:ListItem> <asp:ListItem Selected="True">Normal</asp:ListItem> <asp:ListItem>High</asp:ListItem> </asp:DropDownList></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> Body</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtBody" runat="server" Columns="40" TextMode="MultiLine"></asp:TextBox></td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1">Action</td> <td bgcolor="#FFFFFF"><asp:Button ID="btnSubmit" runat="server" Text="Send Email" OnClick="btnSubmit_Click" /></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1">Status</td> <td bgcolor="#FFFFFF" class="basix"><asp:Literal ID="litStatus" runat="server"></asp:Literal></td> </tr> </table> |
The flow for the code behind page is as follows.
Imports System.Net.Mail Partial Class _Default Inherits System.Web.UI.Page Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Try Dim SendFrom As MailAddress = New MailAddress(txtFrom.Text) Dim SendTo As MailAddress = New MailAddress(txtTo.Text) Dim MyMessage As MailMessage = New MailMessage(SendFrom, SendTo) MyMessage.Subject = txtSubject.Text MyMessage.Body = txtBody.Text Select Case ddPriority.SelectedValue Case "Low" MyMessage.Priority = MailPriority.Low Case "Normal" MyMessage.Priority = MailPriority.Normal Case "High" MyMessage.Priority = MailPriority.High End Select Dim emailClient As New SmtpClient(txtSMTPServer.Text) emailClient.Send(MyMessage) litStatus.Text = "Message Sent" Catch ex As Exception litStatus.Text = ex.ToString() End Try End Sub End Class |
This tutorial will show you how to send a simple email message with authentication using ASP.NET 2.0 and VB.NET
Sending a email with Priorities using ASP.NET 2.0 and VB.NET is actually very simple.
First, you will need to import the
System.Net.Mail namespace.
The
System.Net.Mail namespace contains the
SmtpClient and
MailMessage Classes that we need in order to send the email and specify the user credentials necessary to send authenticated email.
We use the btnSubmit_Click event to do the work.
We then call the emailClient.Send to send the message using the variables from our ASP.NET coded page. We also instantiate a System.Net.NetworkCredential object with the necessary authentication info and then assign that object to the Credentials property of our SmtpClient object.
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Try Dim message As New MailMessage(txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text) Dim emailClient As New SmtpClient(txtSMTPServer.Text) Dim SMTPUserInfo As New System.Net.NetworkCredential(txtSMTPUser.Text, txtSMTPPass.Text) emailClient.UseDefaultCredentials = False emailClient.Credentials = SMTPUserInfo emailClient.Send(message) litStatus.Text = "Message Sent" Catch ex As Exception litStatus.Text = ex.ToString() End Try End Sub |
The front end .aspx page looks something like this:
<table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#5482fc"> <tr> <td height="50" align="center" class="lgHeader1">How to Send Email with Authentication using ASP.NET 2.0 and C#</td> </tr> </table> <br /> <table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#cccccc"> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> To</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtTo" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> From</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtFrom" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1"> SMTP Server</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtSMTPServer" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1">SMTP User</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtSMTPUser" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1">SMTP Pass</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtSMTPPass" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> Subject</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtSubject" runat="server" Columns="50"></asp:TextBox></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> Body</td> <td bgcolor="#FFFFFF"><asp:TextBox ID="txtBody" runat="server" Columns="40" TextMode="MultiLine"></asp:TextBox></td> </tr> <tr> <td align="right" bgcolor="#eeeeee" class="header1">Action</td> <td bgcolor="#FFFFFF"><asp:Button ID="btnSubmit" runat="server" Text="Send Email" OnClick="btnSubmit_Click" /></td> </tr> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1">Status</td> <td bgcolor="#FFFFFF" class="basix"><asp:Literal ID="litStatus" runat="server"></asp:Literal></td> </tr> </table> |
The flow for the code behind page is as follows.
Imports System.Net.Mail Partial Class _Default Inherits System.Web.UI.Page Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Try Dim message As New MailMessage(txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text) Dim emailClient As New SmtpClient(txtSMTPServer.Text) Dim SMTPUserInfo As New System.Net.NetworkCredential(txtSMTPUser.Text, txtSMTPPass.Text) emailClient.UseDefaultCredentials = False emailClient.Credentials = SMTPUserInfo emailClient.Send(message) litStatus.Text = "Message Sent" Catch ex As Exception litStatus.Text = ex.ToString() End Try End Sub End Class |
This tutorial will show you how to display data using ASP.NET 2.0, a repeater control and VB.NET
The Repeater control is a powerful tool and is easy to use.
First, you will need to import the System.Data.SqlClient namespace.
The System.Data.SqlClient namespace contains the SqlCommand and SqlConnection classes that we need in order to connect to our database and to send an SQL command to it.
| Imports System.Data.SqlClient |
We'll put our code in the Page_Load() event.
When the Page_Load() event fires, a new SqlCommand object is instantiated with our connection string and our command.
Afterwards, we will attempt to connect using the Open() method of our cmd.Connection object. Once it is connected we will attempt to execute the command we specified earlier (in this example "SELECT TOP 5 * FROM EMPLOYEES" in the Northwind db).
If all goes well, we will have the results of our SQL query assigned to the rptrExample's DataSource property. Now all we have to do is call the DataBind() method of our rptrExample to bind the data to the control. The data is now ready to be displayed.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load Dim cmd As SqlCommand = New SqlCommand("SELECT TOP 5 * FROM EMPLOYEES", New SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=True;")) Try cmd.Connection.Open() rptrExample.DataSource = cmd.ExecuteReader() rptrExample.DataBind() cmd.Connection.Close() cmd.Connection.Dispose() Catch ex As Exception lblStatus.Text = ex.Message End Try End Sub End Class |
We have to add a few tags on the front end of the .aspx page to place where we want the Repeater control to display its bound data. We also specify what part of the data from the data set we would like to display (in this case, "DataItem.firstname"). The front end .aspx page looks something like this:
<table width="600" border="0" align="center" cellpadding="5" cellspacing="1" bgcolor="#cccccc"> <tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> Repeated Employee First Name Data:</td> <td bgcolor="#FFFFFF"> <asp:Repeater ID="rptrExample" runat="server"> <ItemTemplate> <br /> <%# DataBinder.Eval(Container, "DataItem.firstname") %> <br /> </ItemTemplate> </asp:Repeater> <asp:Label ID="lblStatus" runat="server"></asp:Label></td> </tr> </table> |
The flow for the code behind page is as follows.
Imports System Imports System.Data Imports System.Configuration Imports System.Web Imports System.Web.Security Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Web.UI.WebControls.WebParts Imports System.Web.UI.HtmlControls Partial Public Class _Default : Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load Dim cmd As SqlCommand = New SqlCommand("SELECT TOP 5 * FROM EMPLOYEES", New SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=True;")) Try cmd.Connection.Open() rptrExample.DataSource = cmd.ExecuteReader() rptrExample.DataBind() cmd.Connection.Close() cmd.Connection.Dispose() Catch ex As Exception lblStatus.Text = ex.Message End Try End Sub End Class |
This tutorial will show you how to display data using the .NET GridView Control, ASP.NET 2.0 and VB.NET
The GridView control is a powerful tool and is simple to implement.
First, you will need to import the System.Data.SqlClient namespace.
The System.Data.SqlClient namespace contains the SqlCommand and SqlConnection classes that we need in order to connect to our database and to send an SQL command to it.
| Imports System.Data.SqlClient |
We'll put our code in the Page_Load() event.
When the Page_Load() event fires, a new SqlCommand object is instantiated with our connection string and our command.
Afterwards, we will attempt to connect using the Open() method of our cmd.Connection object. Once it is connected we will attempt to execute the command we specified earlier (in this example "SELECT TOP 5 firstname,lastname,hiredate FROM EMPLOYEES" in the Northwind db).
If all goes well, we will have the results of our SQL query assigned to the gvwExample's DataSource property. Now all we have to do is call the DataBind() method of our gvwExample to bind the data to the control. The data is now ready to be displayed.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load Dim cmd As SqlCommand = New SqlCommand("SELECT TOP 5 firstname,lastname,hiredate FROM EMPLOYEES", New SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=True;")) Try cmd.Connection.Open() gvwExample.DataSource = cmd.ExecuteReader() gvwExample.DataBind() cmd.Connection.Close() cmd.Connection.Dispose() Catch ex As Exception lblStatus.Text = ex.Message End Try End Sub |
We have to add a few tags on the front end of the .aspx page to place where we want the GridView control to display its bound data. We also specify what part of the data from the data set we would like to display (in this case, the DataItems firstname, lastname, and hiredate") as well as the title we would like to give each data item. The front end .aspx page looks something like this:
<tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> Employee Data Using the GridView Control:</td> <td align="center" bgcolor="#FFFFFF"> <asp:GridView ID="gvwExample" runat="server" AutoGenerateColumns="False" CssClass="basix" > <columns> <asp:BoundField DataField="firstname" HeaderText="First Name" /> <asp:BoundField DataField="lastname" HeaderText="Last Name" /> <asp:BoundField DataField="hiredate" HeaderText="Date Hired" /> </columns> </asp:GridView> <asp:label ID="lblStatus" runat="server"></asp:label></td> </tr> |
The flow for the code behind page is as follows.
Imports System Imports System.Data Imports System.Configuration Imports System.Web Imports System.Web.Security Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Web.UI.WebControls.WebParts Imports System.Web.UI.HtmlControls Imports System.Data.SqlClient Partial Public Class _Default : Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load Dim cmd As SqlCommand = New SqlCommand("SELECT TOP 5 firstname,lastname,hiredate FROM EMPLOYEES", New SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=True;")) Try cmd.Connection.Open() gvwExample.DataSource = cmd.ExecuteReader() gvwExample.DataBind() cmd.Connection.Close() cmd.Connection.Dispose() Catch ex As Exception lblStatus.Text = ex.Message End Try End Sub End Class |
This tutorial will show you how to display data using the .NET DataList Control, ASP.NET 2.0 and VB.NET
The DataList control is an easy to use tool similiar to the Repeater control.
First, you will need to import the System.Data.SqlClient namespace.
The System.Data.SqlClient namespace contains the SqlCommand and SqlConnection classes that we need in order to connect to our database and to send an SQL command to it.
| Imports System.Data.SqlClient |
We'll put our code in the Page_Load() event.
When the Page_Load() event fires, a new SqlCommand object is instantiated with our connection string and our command.
Afterwards, we will attempt to connect using the Open() method of our cmd.Connection object. Once it is connected we will attempt to execute the command we specified earlier (in this example "SELECT TOP 5 firstname,lastname,hiredate FROM EMPLOYEES" in the Northwind db).
If all goes well, we will have the results of our SQL query assigned to the dlExample's DataSource property. Now all we have to do is call the DataBind() method of our dlExample to bind the data to the control. The data is now ready to be displayed.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load Try Dim cmd As SqlCommand = New SqlCommand("SELECT TOP 5 firstname,lastname,hiredate FROM EMPLOYEES", New SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=True;")) cmd.Connection.Open() dlExample.DataSource = cmd.ExecuteReader() dlExample.DataBind() cmd.Connection.Close() cmd.Connection.Dispose() Catch ex As Exception lblStatus.Text = ex.Message End Try End Sub |
We have to add a few tags on the front end of the .aspx page to place where we want the DataList control to display its bound data. Inside of the main DataList tag, we use the
<HeaderTemplate> tag to specify the column titles for our repeated data and the
<ItemTemplate> tag to specify what HTML tags can go around that repeated data (in this case,
<td> tags surround each item). So, the front end .aspx page looks something like this::
<tr> <td width="100" align="right" bgcolor="#eeeeee" class="header1"> Employee Data Using the GridView Control:</td> <td align="center" bgcolor="#FFFFFF"> <asp:GridView ID="gvwExample" runat="server" AutoGenerateColumns="False" CssClass="basix" > <columns> <asp:BoundField DataField="firstname" HeaderText="First Name" /> <asp:BoundField DataField="lastname" HeaderText="Last Name" /> <asp:BoundField DataField="hiredate" HeaderText="Date Hired" /> </columns> </asp:GridView> <asp:label ID="lblStatus" runat=&q |