Geeks With Blogs

News

Microsoft MVP


DZone MVB


Moderator at CodeASP.NET


Quiz Master







free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

Overview

This demo explains how to create a simple ShoutBox using the ASP.NET MultiLine TextBox.  A “ShoutBox” basically allow end users to post commentsin the page. To begin let’s create a WebUserControl and implement our ShoutBox there. 

Why UserControl?

We used WebUserControl so that we can re-use and place the control anywhere in your page by simply dragging it to the WebForm.

Step  1: Creating the Database

In this demo, I presumed that you already have a basic background on how to create a simple database table in SQL Server. In this example I used my own database called SampleDB.mdf which has a Commnents Table and basically contains the following field columns for simplicity:

id – PK – AutoGenerate increment number

Name

Message

 

Step 2: Adding Web User Control

You can follow these steps below to add WebUserControl:

  1. Right Click on the Project and select Add New Item
  2. In the Popup window find and select Web User Control file. See below screen shot
  3. Rename the WebUserControl based on your preference. In this demo I named it “UCShoutBox”
  4. Click Add button to create the WebUserControl

Step 3: Setting up the GUI  in the Web User Control

Just for the simplicity of this demo, I set up the UserControl like this:

<%@ Control Language="C#" AutoEventWireup="true" 
                          CodeFile="UCShoutBox.ascx.cs" 
                          Inherits="UCShoutBox" %>

<fieldset> <legend>Leave Comments Here</legend>
    <table>
        <tr>
            <td><asp:TextBox ID="TextBoxPrintMessage" runat="server"
                             TextMode="MultiLine" 
                             Width="200px" Height="300px"/></td>

        </tr>
        <tr>
            <td>*Name</td>
        </tr>
        <tr>
            <td><asp:TextBox ID="TextBoxName" runat="server"/></td>
        </tr>
        <tr>
            <td>*Message</td>
        </tr>
        <tr>
            <td><asp:TextBox ID="TextBoxMessage" runat="server"
                             TextMode="MultiLine" 
                             Width="200px" Height="100px"/></td>
        </tr>
    </table>
    Fields with * are required.<br />
    <asp:Button ID="ButtonPost" runat="server" Text="Post"
                OnClick="ButtonPost_Click" />
</fieldset>

Note: From above declaration, you will noticed that we have set the TextMode  property to MultiLine in the TextBoxPrintMessage  and TextBoxMessage.  Basically TextBoxPrintMessage in our ShoutBox and TextBoxMessage is place where a use can type the message to be posted in the ShoutBox.

Step 4: Setting up the Connection String

In your webconfig file set up the connection string there as shown below:

<connectionStrings>
    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;
                             AttachDbFilename=|DataDirectory|\SampleDB.mdf;
                             Integrated Security=True;User Instance=True" 
                             providerName="System.Data.SqlClient"/>
</connectionStrings>

Note: DBConnection is the name of the Connection String that we can use as a reference in our codes.

In code behind, you can reference that connection string like this:

private string GetConnectionString(){
   return ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
}

 

GetConnectionString() is method that returns the Connection string configured from the web.config file.

Step 5:  Populating the TextBox “ShoutBox”  with data

Here are the code blocks for populating the ShoutBox with data from the database.

private void PopulateTextBox(){

        DataTable dt = new DataTable();
        string name = string.Empty , message = string.Empty;
        StringBuilder sb = new StringBuilder(string.Empty);
 
        SqlConnection conn = new SqlConnection(GetConnectionString());
        try
        {
            conn.Open();
            string sqlStatement = "SELECT * FROM Comments";
            SqlCommand cmd = new SqlCommand(sqlStatement, conn);
            SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);

            sqlDa.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //get the data stored from the DataTable
                    name = dt.Rows[i]["Name"].ToString();// where Name is the FieldName from database
                    message = dt.Rows[i]["Message"].ToString();
                    sb.AppendFormat("Name:{0}Date Posted:{1}{2}", name + Environment.NewLine
                                           , DateTime.Now.ToShortDateString() + Environment.NewLine
                                           , message + Environment.NewLine);
                }
                // get the concated and formatted values from string builder and display the result in TextBoxPrintMessage

                TextBoxPrintMessage.Text = sb.ToString();
            }
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Fetch Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
        }
 }

 

The code above basically populates the ShoutBox with the data from the database with the name, date posted and the message.

Populating the ShoutBox on initial load

protected void Page_Load(object sender, EventArgs e){
        if (!IsPostBack)
        {
            PopulateTextBox();
        }
}

Step 6: Adding new Post and Insert it to Database

Here’s the code block for inserting the newly added post to the database

private void AddNewPost(string name, string message){

        SqlConnection conn = new SqlConnection(GetConnectionString());
        string sqlStatement = string.Empty;

        sqlStatement = "INSERT INTO Comments" +
                       "(Name,Message)" +
                       "VALUES (@Name,@Message)";
        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sqlStatement, conn);
            cmd.Parameters.AddWithValue("@Name", name);
            cmd.Parameters.AddWithValue("@Message", message);
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
        }
}

 

The AddNewPost() is a  method that  takes two parameters (name and message). Those parameters will be passed in the query and insert it to the database.

Not let’s call the method AddNewPost() on Button_Click event.  Here’s the code block below.

protected void ButtonPost_Click(object sender, EventArgs e)
{

     // Check for empty values fieds before inserting the record
 if (TextBoxName.Text != string.Empty && TextBoxMessage.Text != string.Empty)
 {
     //insert new post to database
     AddNewPost(TextBoxName.Text.Trim(), TextBoxMessage.Text.Trim());
     //Populate the TextBox to reflect changes made
     PopulateTextBox();
  }
  else
  { 
     //display message if the field was not supplied
     Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Script",
     "alert('Please supply the required  fields!');", true);
        }
}

 

As you have noticed above, we called the method AddNewPost() and pass the values from the TextBoxes as the paramters. We aslo called the method PopulateTextBox() again in order to reflect the newly added post in the ShoutBox.

Step 7: Adding the WebUserControl in the page

You can add the WebUserControl in the WebForm by simply dragging it to the area of the WebForm.

After adding it to the WebForm then you can compile and run the page. Here’s the screen shot below:

 

That’s It!

Hope you will find this example useful!

 

Technorati Tags: ,,
Posted on Tuesday, February 24, 2009 5:50 PM ADO.NET , ASP.NET , C# | Back to top


Comments on this post: Creating a Simple ShoutBox with MultiLine TextBox

# re: Creating a Simple ShoutBox with MultiLine TextBox
Requesting Gravatar...
Nice job!
Left by hans on Dec 06, 2009 4:53 AM

# re: Creating a Simple ShoutBox with MultiLine TextBox
Requesting Gravatar...
Very good...
Left by naveenkumar on Jun 02, 2010 12:02 AM

# re: Creating a Simple ShoutBox with MultiLine TextBox
Requesting Gravatar...
This is great man keep it up!
Left by Pinoy on Jun 25, 2010 7:33 PM

# re: Creating a Simple ShoutBox with MultiLine TextBox
Requesting Gravatar...
so great ..
Left by maria on Jul 10, 2010 2:09 PM

# re: Creating a Simple ShoutBox with MultiLine TextBox
Requesting Gravatar...
Can somebody tell me y I have this errors when I followed the instructions above?

c:\Users\User\Documents\1578\IT1578-forthforum\shoutbox.ascx.cs(33,9): error CS0246: The type or namespace name 'StringBuilder' could not be found (are you missing a using directive or an assembly reference?)
c:\Users\User\Documents\1578\IT1578-forthforum\shoutbox.ascx.cs(33,32): error CS0246: The type or namespace name 'StringBuilder' could not be found (are you missing a using directive or an assembly reference?)
c:\Users\User\Documents\1578\IT1578-forthforum\shoutbox.ascx.cs(35,9): error CS0246: The type or namespace name 'SqlConnection' could not be found (are you missing a using directive or an assembly reference?)
c:\Users\User\Documents\1578\IT1578-forthforum\shoutbox.ascx.cs(35,34): error CS0246: The type or namespace name 'SqlConnection' could not be found (are you missing a using directive or an assembly reference?)
c:\Users\User\Documents\1578\IT1578-forthforum\shoutbox.ascx.cs(40,13): error CS0246: The type or namespace name 'SqlCommand' could not be found (are you missing a using directive or an assembly reference?)
c:\Users\User\Documents\1578\IT1578-forthforum\shoutbox.ascx.cs(40,34): error CS0246: The type or namespace name 'SqlCommand' could not be found (are you missing a using directive or an assembly reference?)
c:\Users\User\Documents\1578\IT1578-forthforum\shoutbox.ascx.cs(41,13): error CS0246: The type or namespace name 'SqlDataAdapter' could not be found (are you missing a using directive or an assembly reference?)
c:\Users\User\Documents\1578\IT1578-forthforum\shoutbox.ascx.cs(41,40): error CS0246: The type or namespace name 'SqlDataAdapter' could not be found (are you missing a using directive or an assembly reference?)
c:\Users\User\Documents\1578\IT1578-forthforum\shoutbox.ascx.cs(76,9): error CS0246: The type or namespace name 'SqlConnection' could not be found (are you missing a using directive or an assembly reference?)
c:\Users\User\Documents\1578\IT1578-forthforum\shoutbox.ascx.cs(76,34): error CS0246: The type or namespace name 'SqlConnection' could not be found (are you missing a using directive or an assembly reference?)
c:\Users\User\Documents\1578\IT1578-forthforum\shoutbox.ascx.cs(87,13): error CS0246: The type or namespace name 'SqlCommand' could not be found (are you missing a using directive or an assembly reference?)
c:\Users\User\Documents\1578\IT1578-forthforum\shoutbox.ascx.cs(87,34): error CS0246: The type or namespace name 'SqlCommand' could not be found (are you missing a using directive or an assembly reference?)
Left by jw on Jan 27, 2011 1:51 AM

# re: Creating a Simple ShoutBox with MultiLine TextBox
Requesting Gravatar...
@jw,

Be sure to declare System.Text.
Left by Vinz on Jan 27, 2011 3:43 PM

# re: Creating a Simple ShoutBox with MultiLine TextBox
Requesting Gravatar...
Why?------Fetch Error:Invalid object name 'comments'.


Line 70: string msg = "Fetch Error:";
Line 71: msg += ex.Message;
Line 72: throw new Exception(msg);
Line 73: }
Line 74: finally

I need to change the word comments from----- string sqlStatement = "SELECT * FROM comments"; ?
If yes, I shall change it to? I searched on internet and found out that I shall change comments to the table name. But, how and where to assign the table? Im confused.
Left by merry on Jan 27, 2011 11:06 PM

# re: Creating a Simple ShoutBox with MultiLine TextBox
Requesting Gravatar...
THANK YOU Very Much! Its a nice job done. :)

Left by jw on Jan 27, 2011 11:21 PM

# re: Creating a Simple ShoutBox with MultiLine TextBox
Requesting Gravatar...
@merry,

You need to create a Database first and then create a Table and name it whatever you want. In this example I just named the table as Comments for storing the user comments data.
Left by Vinz on Jan 27, 2011 11:27 PM

# re: Creating a Simple ShoutBox with MultiLine TextBox
Requesting Gravatar...
Hey, how do i declare system.text?
sorry newbie here. i got the following errors:

Error 1 Expected class, delegate, enum, interface, or struct c:\users\boonleng\documents\visual studio 2010\Projects\WebApplication2\WebApplication2\WebUserUCShoutbox.ascx.cs

Error 2 Identifier expected
c:\users\boonleng\documents\visual studio 2010\Projects\WebApplication2\WebApplication2\WebUserUCShoutbox.ascx.cs

Error 3 Type or namespace definition, or end-of-file expected c:\users\boonleng\documents\visual studio 2010\Projects\WebApplication2\WebApplication2\WebUserUCShoutbox.ascx.cs
Left by BL on Jul 20, 2011 7:47 PM

# re: Creating a Simple ShoutBox with MultiLine TextBox
Requesting Gravatar...
@BL,

Declare the namespace at the very top of your code before the class declaration.
Left by Vinz on Jul 21, 2011 1:42 PM

# re: Creating a Simple ShoutBox with MultiLine TextBox
Requesting Gravatar...
<%@ Import Namespace = "System.Text" %>
Left by Sim on Dec 29, 2011 3:04 AM

# re: Creating a Simple ShoutBox with MultiLine TextBox
Requesting Gravatar...
Hi, is there an easy way to alter this code so that once a user posts his message, it automatically appears on every other viewers page, rather than how it is at the moment, where you have to refresh your web page in order to view each message?

Thanxx
Left by Shimm on Dec 29, 2011 5:29 AM

# re: Creating a Simple ShoutBox with MultiLine TextBox
Requesting Gravatar...
that was bad fuck
Left by mital on Jul 13, 2012 6:48 PM

# re: Creating a Simple ShoutBox with MultiLine TextBox
Requesting Gravatar...
Parser Error Message: Could not load type 'ShoutBox.Global.asax'
Left by gsvirdi on Jul 16, 2012 7:58 PM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net