Create Your Own Guestbook In ASP.NET


Environment: ASP, .NET


Recently, I was working on my Web site and I wanted to implement a guestbook. So, I searched the Web to get the best guestbook for my Web site. But then I thought, "Hey, I am a developer. Why not create my own?" It was very easy to create a guestbook and you can do it, too. In this article, I will show you how you can easily create a guestbook. To understand the article, I assume that you have already knowledge about the basics of ASP.NET programming and XML/XSL skills.


So, what do we need to create a guestbook? We need two webforms: one to enter the name, e-mail, comments, and so forth; the other is used to display the comments signed in the guestbook. Of course, we can make this in one webform, but to have clean code, I will use two webforms with several codebehind files, which I discuss later. Then we need a database, which holds the information for us. I have used a simple XML file (database) to store the information entered by the user. To visualize the XML, we also use the XSL technique. In summary, we need the following items:

  • Two webforms
  • Codebehind
  • Database
  • XSL

In a guestbook, it is usually fully sufficient to store the name, location, e-mail, Web site, and some comment lines. Of course, you can have more fields to store, but I think these are enough. This data is stored in the XML file. So, according to that, our XML can look something like this:


01: <?xml version="1.0" encoding="ISO-8859-1"?>
02: <guestbook>
03:   <guest>
04:   <name>Sonu Kapoor</name>
05:   <location>Germany</location>
06:   <email></email>
07:   <website></website>
08:   <comment>This guestbook is written by Sonu Kapoor.
09:   I hope you like it. To learn how to create such a
10:   guestbook, read the whole story on my Web site.</comment>
11:   </guest>
12: </guestbook>

The Webforms, Part I: Signing the Guestbook

To sign a guestbook, we allow the user to enter some information. This can be done in a simple webform. In our example, this is the guestbook.aspx file. I use the following fields in the webform; the user can fill them in.

  • Name
  • Location
  • Email
  • Website
  • Comment

The first Webform: guestbook.aspx:

01: <% @Page Language="C#" Debug="true" Src="Guestbook.cs"
                           Inherits="Guestbook" %>
02: <form runat="server">
03: ...
04: ...doing some visualisation stuff
05: ...
06: <ASP:Textbox id="name" size="64" runat="server"/>
08: <asp:RequiredFieldValidator id="nameRequired" runat="server"
09: ErrorMessage="You must enter a value into textbox1"
                  Display="dynamic">Enter name
10: </asp:RequiredFieldValidator>
12: <ASP:Textbox id="location" size="64" runat="server"/>
14: <asp:RequiredFieldValidator id="locationRequired"
         runat="server" ControlToValidate="location"
15: ErrorMessage="You must enter a value into textbox1"
         Display="dynamic">Enter location
16: </asp:RequiredFieldValidator>
18: <ASP:Textbox id="website" size="64" runat="server"/>
19: <ASP:Textbox id="email" size="64" runat="server"/>
20: <ASP:Textbox id="comment" TextMode="Multiline" columns="50"
         rows="10" wrap="true" runat="server"/>
22: <asp:RequiredFieldValidator id="commentRequired"
         runat="server" ControlToValidate="comment"
23: ErrorMessage="You must enter a value into textbox1"
         Display="dynamic">Enter comment
24: </asp:RequiredFieldValidator>
26: <ASP:Button id="submit" runat="server" Text="Submit"
27: <ASP:Button id="reset" runat="server" Text="Reset"/>
28: ...
29: ...doing some visualisation stuff
30: ...
31: </script>
32: </form>

To avoid confusing you with unnecessary code, I have removed the visualisation tags, such as table, table header, and so forth from this example. Of course, these are all included in the example download. As we only display a form with some fields and buttons, you don't see any real programming code. This is all hidden in the codebehind. I assume you already know the technique of codebehind. In line 1 I have set the SRC attribute to let the file know that we are using the codebehind file Guestbook.cs and I have set also the attribute Inherits with the corresponding classname. This attribute is used to let the file know which class has to be inherited. In lines 6, 12, and 18-20, I have implemented the required textfields. Please remember that if you want to use the same variables in the codebehind, they need to have the same ID in both files and must be declared as public. In lines 8, 14, and 22 I have used the ASP.NET validator controls. These validator controls check whether the user has entered any value in the textfields, without doing a round-trip to the server. This code is executed on the client side.

In line 26, I have implemented a submit button with an OnClick event called Save_Comment. This event is used to store the information entered by the user to the XML file. The function of this event is available in the Guestbook.cs. In line 27n I have only implemented a reset button. This is all; nothing more has to be done in the webform. If you run guestbook.aspx, you should see a webform like this:

By now, you have seen how to display a webform, but you have not yet seen the code that is handling the event in guestbooks.cs.

The Codebehind: guestbook.cs:

01: using System;
02: using System.Web;
03: using System.Web.UI;
04: using System.Web.UI.WebControls;
05: using System.Xml;
07: public class Guestbook : Page
08: {
09:   // Create the required webcontrols with the same name as
      // in the guestbook.aspx file
10:   public TextBox name;
11:   public TextBox location;
12:   public TextBox email;
13:   public TextBox website;
14:   public TextBox comment;
16:   public void Save_Comment(object sender, EventArgs e)
17:   {
18:     // Everything is all right, so let us save the data
        // into the XML file
19:     SaveXMLData();
21:     // Remove the values of the textboxes
22:     name.Text="";
23:     location.Text="";
24:     website.Text="";
25:     email.Text="";
26:     comment.Text="";
27:   }
28: }
30: private void  SaveXMLData()
31: {
32:   // Load the XML file
33:   XmlDocument xmldoc = new XmlDocument();
34:   xmldoc.Load( Server.MapPath("guestbook.xml") );
36:   //Create a new guest element and add it to the root node
37:   XmlElement parentNode = xmldoc.CreateElement("guest");
38:   xmldoc.DocumentElement.PrependChild(parentNode);
40:   // Create the required nodes
41:   XmlElement nameNode     = xmldoc.CreateElement("name");
42:   XmlElement locationNode = xmldoc.CreateElement("location");
43:   XmlElement emailNode    = xmldoc.CreateElement("email");
44:   XmlElement websiteNode  = xmldoc.CreateElement("website");
45:   XmlElement commentNode  = xmldoc.CreateElement("comment");
47:   // retrieve the text
48:   XmlText nameText     = xmldoc.CreateTextNode(name.Text);
49:   XmlText locationText = xmldoc.CreateTextNode(location.Text);
50:   XmlText emailText    = xmldoc.CreateTextNode(email.Text);
51:   XmlText websiteText  = xmldoc.CreateTextNode(website.Text);
52:   XmlText commentText  = xmldoc.CreateTextNode(comment.Text);
54:   // append the nodes to the parentNode without the value
55:   parentNode.AppendChild(nameNode);
56:   parentNode.AppendChild(locationNode);
57:   parentNode.AppendChild(emailNode);
58:   parentNode.AppendChild(websiteNode);
59:   parentNode.AppendChild(commentNode);
61:   // save the value of the fields into the nodes
62:   nameNode.AppendChild(nameText);
63:   locationNode.AppendChild(locationText);
64:   emailNode.AppendChild(emailText);
65:   websiteNode.AppendChild(websiteText);
66:   commentNode.AppendChild(commentText);
68:   // Save to the XML file
69:   xmldoc.Save( Server.MapPath("guestbook.xml") );
71:   // Display the signed guestbook to the user
72:   Response.Redirect("viewguestbook.aspx");
73:   }
74: }

So far, concerning the codebehind file, what really happens here? You won't believe it, but not much. In lines 1-3, I have implemented the minimal required namespaces that are needed to get access to several functions. In line 7, I have created a new class called Guestbook; please notice this is the class which is inherited by the guestbook.aspx file. Line 10-14 declares five public variables of type type textbox. Please remember also here that these names have to be identical to the textboxes created in guestbook.aspx. In line 16, you can see the event Save_Comment, which is fired by the submit button of the guestbook.aspx file. This event is used to save the data.

The Saving Process

The SaveXMLData() function saves the information for us. Because we are using a XML database to store the information, we use the XmlDocument, XmlElement, and XmlText classes. These classes provide the necessary functions. Lines 33-34 create a new XMLDocument class object and loads the guestbook.xml file. In lines 41-45, the required nodes are created with the CreateElement function. Lines 48-52 retrieve the information the user entered and store them to an object of XmlText. In lines 55-59, I have used the AppendChild function with the main XmlDocument object. This function stores the created nodes without the values. Finally, in lines 62-68, the values are stored in the nodes we just created. In line 69, all changes are saved to the guestbook.xml. Line 72 redirects the page to the viewguestbook.aspx, to display the stored comment.

The Webforms, Part II: Viewing the Guestbook

To view the guestbook, I have created another webform. Take a look at the second webform.


01: <% @Page Language="C#" Debug="true" Src="ViewGuestbook.cs"
                           Inherits="ViewGuestbook" %>

As you see, I am not doing very much in the webform. I have just called the codebehind file ViewGuestbook.cs. So, please take a look at this file.

The Codebehind: ViewGuestbook.cs:

01: using System;
02: using System.Web;
03: using System.Web.UI;
04: using System.Web.UI.WebControls;
05: using System.Xml;
06: using System.Xml.Xsl;
07: using System.IO;
09: public class ViewGuestbook : Page
10: {
11:   private void Page_Load(object sender, System.EventArgs e)
12:   {
13:     //Load the XML file
14:     XmlDocument doc = new XmlDocument( );
15:     doc.Load( Server.MapPath("guestbook.xml") );
17:     //Load the XSL file
18:     XslTransform xslt = new XslTransform();
19:     xslt.Load( Server.MapPath("guestbook.xsl") );
21:     string xmlQuery="//guestbook";
22:     XmlNodeList nodeList=doc.DocumentElement.SelectNodes(
24:     MemoryStream ms=new MemoryStream();
25:     xslt.Transform( doc, null, ms);
26:     ms.Seek( 0, SeekOrigin.Begin );
28:     StreamReader sr = new StreamReader(ms);
30:     //Print out the result
31:     Response.Write(sr.ReadToEnd());
32:   }
33: }

I have created this class to display all comments to the user. Lines 1-7 are again used to implement the required namespaces. Because we are using XSL for the visualisation, we have to include the namespace System.Xml.Xsl. Line 9 creates a new class called ViewGuestbook, with a private built-in function called Page_Load. This function is always called when the page loads or when the user performs a refresh. The function again loads guestbook.xml in line 15. The XslTranform class is used to transform the XML elements into HTML. In lines 18-19, I load guestbook.xsl with the help of a XslTransform object. Line 22 creates a new object of class XmlNodeList. With the help of this class, we can select the required nodes. In line 24, I have used the MemoryStream class, which is available via the namespace System.IO. This class is used to create a stream that has memory as a backing store. With the function Transform in line 25, I have assigned the XML data to the memorystream. The Seek function in line 26 sets the current position to zero. In line 28, I have created an object of the class StreamReader. This class is used to read the stream. Line 31 prints then the result with the help of the ReadToEnd() function. This function reads the stream from the current position to the end. If you run viewguestbook.aspx, you should see a webform like this:


As already mentioned, we use XSL to transform from XML to HTML. I assume that you already have knowledge about XSLT, so I will only discuss the important things. I have only used an XSL for-each loop to iterate through all the guests. This looks something like this:

01: <xsl:for-each select="//guest">
02:   <xsl:apply-templates select="name"/>
03: </xsl:for-each>

In the loop, I call the XSL template name, which looks something like this:

01: <xsl:template match="name">
02:   <xsl:value-of select='.'/>
03: </xsl:template>


As you see, it is not very difficult to create a guestbook. You can see the guestbook live on my Web site. I hope to release further versions of the Guestbook with your help. Please send feedback to


Download demo project - 4 Kb

About the Author

Sonu Kapoor

Sonu Kapoor is an ASP.NET MVP and MCAD. He is the owner of the popular .net website DotNetSlackers publishs the latest .net news and articles - it contains forums and blogs as well. His blog can be seen at:


  • グッチ グッチ 財布 グッチ バッグ コーチ コーチ バッグ コーチ 財布

    Posted by scgchurtis on 07/19/2013 06:00pm

    財布 ブラック Prada 財布 夫であるパチンコ店経営者の西村拓郎氏が COACH 財布 面白ないと退団するかもしれませんね 新作 エキゾティックな甘さが印象的です [url=]グッチ バッグ[/url] [url=]コーチ セール[/url] コーチ トート プラダ chanel 財布 プラダ バッグ プラダ アウトレット miumiu バッグ chanel 財布 グッチバッグ シャネル 財布 新作 コーチ財布

  • Phim chieu rap

    Posted by marfomift on 07/18/2013 01:24pm

    What Are The Best 3 D Blu Ray Movies To Take Home?T-Pain Resuscitates Freaknik For Cartoon MusicalPolitical Movies Tell The True Statement Some Of The Time About PoliticsFour months after Teletoon Canada Inc. announced Cartoon Network and Adult Swim were coming to Canada, іt; has finally come to fruition. Four months after Teletoon Canada Inc. announcedCartoon Network and Adult Swim were coming to Canada, it has finally come to fruition. One can never have enough "Robot Chicken." One can never have enough "Robot Chicken." Will 2012 Be A Tragedy At The Movies? _____________

  • Rap phim

    Posted by marfomift on 07/15/2013 04:24am

    This book contains amusing, insightful considerations of films about Venice, New York, the Post Office, art, gangsters and newspapers: "The B picture star Elaine Shepherd quit Hollywood to become a reporter and even wrote an autobiography called Forgive Us Our Press Passes." His wit is as sharp as his knowledge. Yoυ are indisputable to hold a dour way, or at the dramaturgy.Six Out Of 10 Movies Pullulated Via Netflix: StudyThe best love is the kind that аw;аken;ѕ the soul and makes us reach for more; that plants a fire in our hearts and brings peace to οur; minds... That's what you've given me аn;ԁ that's what I hope to give to you forever. Hollywood has produced many good movies that have bееn; huge blockbusters and also have a huge fan following. There are so many movies with touching plots and soothing music that it is quite impossible to list all of them. Top 10 Best Romantic MoviesRomantic movies is one such popular genre that is loved by everyone. The best, most enduring movies are those that capture a piece of universal human experience. Something that everyone has experienced in their own lives. We love to see ourselves reflected on the big screen, either realistically, or as our fantasy selves. And would couƖd; be more universally human than the emotion οf; Love? So, without further ado, here's a list οf; favorite Romantic movies, sure to warm even the chіƖƖіe;st; hearts... Call іt; just another 1980'ѕ teen drama. In That Location are countless οf; romantic funninesses, you can relish toɡеth;еr; on Valentine's Day?The Top Ten Romantic Movies Of All Time _____________

  • Phim chieu rap

    Posted by marfomift on 07/12/2013 12:55pm

    Animation is the rapid succession of a series of images in order to create an illusion of a moving pictυre;. In other words, it is an optical impression of mοt;іοn; resulting from the phenomenon of persistence of vision. The movіn;ɡ pictures are produced through a string of consecutive images that reproduce motion by each image showing the next in a gradual progression of steps. If a series of 24 or less cartoon images run per second, it will result in a cartoon animation. The Royal Tenenbaums9 28 Days Later5.The Best Ryan Gosling Movies 2013This spy camera dvr designed into pretty cartoon style, just like a cartoon decoration which make users D. I. Y to install it freely. Intruders can not easily be found. Moreover, it is easy to operate. This cartoon smart rеc;οrd;еr; сa;n; also use as a webcam and play on computer. Uѕеr;ѕ can take it to have video chat with relatives and friends. Also it сa;n; be used to store recorded video. And simultaneously record thе tіme; and date. Accompany with memory expansion function, it can meet the needs of photographing mostly. Until the past few years South Africa has been better known as a location for shootіng; foreign films rаth;еr; than as a film-maker in its own right. The festival, which will take place in February, is aimed at show-casing an emerging generation of local film-makers who arе beginning to make waves on thе international scene. Irvin, реrha;рs; best known for his iconic TV ѕe;r;іe;ѕ Tinker, Tailor, Soldier, Spy - now very much back in fashion but wіth;οut; Alec Guinness - has been greatlу impressed by the talent anԁ creativity he has seen from both white and black South Africans. French Muslims Dismiss Phones For Cartoon Protest _____________

  • order Olanzapine online

    Posted by ZyprexaOnline78 on 07/09/2013 10:19am

    There are no instant way can heal anxiety disorders. purchase generic Zyprexa Olanzapine online buy Zyprexa online no prescription Remember, anxiety is borne out of a very natural feeling - fear. [url=]order Zyprexa online[/url] Doctor visits and wellness checkups are covered under most health insurance plans, as are periodic hearing and vision screenings.

  • buy Zyprexa online

    Posted by BuyZyprexa46 on 07/08/2013 11:57pm

    We have all experienced anxiety and panic attacks. buy cheap Zyprexa online without a prescription purchase Olanzapine online without a prescription The relaxation response triggered by this technique can quell the nasty symptoms of the disorder. [url=]purchase Olanzapine online[/url] In terms of insurance coverage for the treatment, most health insurance plans cover the costs.

  • Gia cuu nha trang

    Posted by marfomift on 07/08/2013 08:19pm

    Coming this June Sony Pictυres; will be out with White House Down starring Channing Tatum and Jamie Foxx. In the movie, Capitol Policeman John Cale Channing Tаt;υm; has just been denied his dream job with the Secret Service of protecting President James Sawyer Jamie Foxx. Not wanting to let down his Ɩіtt;Ɩe; girl with the news, he takes her on a tour of the White House, when the complex is overtaken by а heavily armed terrorist paramilitary group. Now, with the nation's government falling into chaos and time running out, it's up to Cale tο save the president, his daughter, and the country.White House Down Trailer: We've Witnessed This Somewhere Before, Certainly?White House DownDirector Roland Emmerich was born in Germany, but for the last 17 years he's had his sight and sights set οn; the White House. DirectorRoland Emmerichwas born in Germany, but for the last 17 years he's had his sight and sights set οn; the White House. Emmerich indeed has experience causing carnage οn; 1600 Pennsylvania Avenue. The first "White House Down" trailer premieres exclusively on Huff Post Entertainment; watch it above. Emmerich indeed has experience causing carnage on 1600 Pennsylvania Avenue. A Rachel McAdams y Chаnn;іng; Tatum de" Magic Mike" en Berln, Alemania, el jueves 12 de julio, 2012.In the upcoming action film "White House Down," from ԁir;еc;tor; Rolanԁ Emmerich "2012" and "Independence Day" Channing Tatum stars as а United States Secret Service аg;еnt; who must rescue the President of the United States played by Jamie Foxx from а paramilitary group that has taken over the White House. Foxx also stars alongside Christoph Waltz and Leonardo DiCaprio in director Quentin Tarantino's much anticipated Western "Django Unchained" which opens on December 25, 2012. He also wrote the screenplay for "The Amazing Spider Man 2" and the upcoming "Robobcop" remake. During the event which I saw in New York City on June 8. _____________ White house down

  • order Zoloft 25mg online

    Posted by BuyZoloft3 on 07/07/2013 08:51pm

    zoloft alcohol craving Order Zoloft Without a Prescription zoloft used treat pmdd [url=] Order Zoloft at Discounted Price [/url] side effects for zoloft medication Buy Cheap Sertraline Anxiety Treatment zoloft withdrawal rebound depression

  • order Prozac 40mg online

    Posted by ProzacOnline78 on 07/05/2013 12:53am

    WebMD Health Experts and Community purchase Prozac online no prescription order cheap Prozac online Chronic depression generally requires long-term treatment. And while medications are highly effective, some people choose to treat the condition naturally. There are natural ways to ease chronic depression. Stress management techniques (breathing exercises, massages, hobbies) may reduce anxiety and alleviate depression episodes. Additionally, establishing an exercise routine can increase dopamine and serotonin and improve a person's mood and outlook. Positive thinking can also ease chronic depression, and talking with a therapist can help a person pinpoint situations or events that bring on depression. [url=]buy Prozac 20mg online without a prescription[/url] What Are the Symptoms of Depression?

  • Purchase Cheap Zyprexa Online No Rx

    Posted by Stefani531 on 07/04/2013 10:21am Purchase Zyprexa at Discounted Price - zyprexa depression treatment

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • Agile methodologies give development and test teams the ability to build software at a faster rate than ever before. Combining DevOps with hybrid cloud architectures give teams not just the principles, but also the technology necessary to achieve their goals. By combining hybrid cloud and DevOps: IT departments maintain control, visibility, and security Dev/test teams remain agile and collaborative Organizational barriers are broken down Innovation and automation can thrive Download this white paper to …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds