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 System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
}
|
GetConnectionString() is method that returns the Connection String.
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();
}
}
|
AddNewPost() is 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 this example is helpful for you guys!