Friday, 9 January 2015

Create Simple Comment Box in ASP.NET





All of us have seen a comment box on various websites. In this Post, we will learn how to create a Simple Comment Box in ASP.NET. For demonstration, I have created a database (named as Database). The following is the table design for creating tbl_Comment.

Let's Begin:
1. Create an Empty ASP.NET Website and Add a Web Form (Default.aspx) to it.
2. Inside of div tag, create a table with 3 columns and 4 rows.
3. Drop the Label control and TextBox Control in the first and second column. Change the TextMode property for the Comment TextBox to MultiLine.
4. Add RequiredFieldValidator for all TextBox in the third column. Add another validation i.e. RegularExpressionValidator for txtEmail TextBox. Set the Validation Expression to Internet e-mail address.
5. Drop Button Control and Set Id as btn_Submit and Text as Post Comment.
Preview:
6. Drop two Repeater Control after the table tag. One for displaying the comments and other for displaying paging.
Default.aspx Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .auto-style1 {
            width: 86px;
        }

        .auto-style2 {
            width: 201px;
        }
    </style>
    <link href="StyleSheet.css" rel="stylesheet" />
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div class="formDesign">
                <table style="width: 100%;">
                    <tr>
                        <td class="auto-style1">Name</td>
                        <td class="auto-style2">
                            <asp:TextBox ID="txtName" runat="server" Width="185px"></asp:TextBox>
                        </td>
                        <td>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName" ErrorMessage="Please Provide Name" ForeColor="#CC0000">*</asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td class="auto-style1">Email</td>
                        <td class="auto-style2">
                            <asp:TextBox ID="txtEmail" runat="server" Width="185px"></asp:TextBox>
                        </td>
                        <td>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtEmail" Display="Dynamic" ErrorMessage="Please Provide Email" ForeColor="#CC0000">*</asp:RequiredFieldValidator>
                            <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtEmail" Display="Dynamic" ErrorMessage="Email ID is Incorrect" ForeColor="#CC0000" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
                        </td>
                    </tr>
                    <tr>
                        <td class="auto-style1">Comment</td>
                        <td class="auto-style2">
                            <asp:TextBox ID="txtComment" runat="server" Height="44px" TextMode="MultiLine" Width="185px"></asp:TextBox>
                        </td>
                        <td>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtComment" ErrorMessage="Please Provide Comment" ForeColor="#CC0000">*</asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td class="auto-style1">&nbsp;</td>
                        <td class="auto-style2">
                            <asp:Button ID="btn_Submit" runat="server" Text="Post Comment" OnClick="btn_Submit_Click" CssClass="buttonSubmit" />
                        </td>
                        <td>&nbsp;</td>
                    </tr>
                </table>
            </div>
            <h4 style="text-decoration:underline;">Comments:</h4>
            <asp:Repeater ID="Repeater1" runat="server">
                <ItemTemplate>
                    <div class="commentbox">
                        <b>
                            <asp:Label ID="Label1" runat="server" Text='<%#Eval("Name") %>'>'></asp:Label></b>&nbsp;(<asp:Label ID="Label2" runat="server" Text='<%#Eval("Email") %>'>'></asp:Label>):<br />
                        <asp:Label ID="Label3" runat="server" Text='<%#Eval("Comment") %>'></asp:Label><br />
                    </div>
                </ItemTemplate>
            </asp:Repeater>
            <div style="overflow: hidden;">
                <asp:Repeater ID="rptPaging" runat="server" OnItemCommand="rptPaging_ItemCommand">
                    <ItemTemplate>
                        <asp:LinkButton ID="btnPage"
                            Style="padding: 8px; margin: 2px; background: #007acc; border: solid 1px blue; font: 8px;"
                            CommandName="Page" CommandArgument="<%# Container.DataItem %>"
                            runat="server" ForeColor="White" Font-Bold="True" CausesValidation="false"><%# Container.DataItem %>
                        </asp:LinkButton>
                    </ItemTemplate>
                </asp:Repeater>
            </div>
        </div>
    </form>
</body>
</html>
Preview:
Default.aspx.cs Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
    string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            fillData();
        }
    }
    //FillData method for filling Repeater Control with Data
    private void fillData()
    {
        SqlConnection con = new SqlConnection(cs);
        con.Open();
        DataTable dt = new DataTable();
        SqlDataAdapter adapt = new SqlDataAdapter("Select * from tbl_Comment Order by Id Desc", con);
        adapt.Fill(dt);
        con.Close();
        PagedDataSource pds = new PagedDataSource();
        DataView dv = new DataView(dt);
        pds.DataSource = dv;
        pds.AllowPaging = true;
        pds.PageSize = 4;
        pds.CurrentPageIndex = PageNumber;
        if (pds.PageCount > 1)
        {
            rptPaging.Visible = true;
            ArrayList arraylist = new ArrayList();
            for (int i = 0; i < pds.PageCount; i++)
                arraylist.Add((i + 1).ToString());
            rptPaging.DataSource = arraylist;
            rptPaging.DataBind();
        }
        else
        {
            rptPaging.Visible = false;
        }
        Repeater1.DataSource = pds;
        Repeater1.DataBind();
    }
    //btn_Submit Click Event
    protected void btn_Submit_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(cs);
        con.Open();
        SqlCommand cmd = new SqlCommand("insert into tbl_Comment(Name,Email,Comment) values(@name,@email,@comment)",con);
        cmd.Parameters.AddWithValue("@name",txtName.Text);
        cmd.Parameters.AddWithValue("@email", txtEmail.Text);
        cmd.Parameters.AddWithValue("@comment", txtComment.Text);
        cmd.ExecuteNonQuery();
        con.Close();
        //Displaying Javascript alert Comment Posted Successfully
        ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Comment Posted Successfully.');window.location='default.aspx';", true);
        fillData();
        txtName.Text = "";
        txtEmail.Text = "";
        txtComment.Text = "";
    }
    public int PageNumber
    {
        get
        {
            if (ViewState["PageNumber"] != null)
                return Convert.ToInt32(ViewState["PageNumber"]);
            else
                return 0;
        }
        set
        {
            ViewState["PageNumber"] = value;
        }
    }
    protected void rptPaging_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        PageNumber = Convert.ToInt32(e.CommandArgument) - 1;
        fillData();
    }
}
Final Preview:
Hope you like it. If you have any query comment it below. Thanks.
[Download Source Code via Google Drive]

12 comments:

  1. hi Anoop and thx for the tutorial, but im facing one problem, after clicking on the ok button in the pop up box, all the comments i have posted disappear, i can't see any comment. help me plz

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Replies
    1. This comment has been removed by a blog administrator.

      Delete
  4. Sir after using these codes i got error
    .
    .

    Compiler Error Message: CS1061: 'ASP.default_aspx' does not contain a definition for 'Repeater1_ItemCommand' and no extension method 'Repeater1_ItemCommand' accepting a first argument of type 'ASP.default_aspx' could be found (are you missing a using directive or an assembly reference?)

    what should i do?

    ReplyDelete
  5. sir my previous problem is solved .. but now i get this error:-

    Cannot insert the value NULL into column 'Id', table 'Database.dbo.tbl_Comment'; column does not allow nulls. INSERT fails.
    The statement has been terminated.

    plz provide me solution

    ReplyDelete
    Replies
    1. you need to provide "auto generate id" functionality to ur Id column as it is primary key.
      because you are not providing any value to Id, it is showing error as it cannot be left null.

      Delete
  6. HELP ME PLEASE I HAVE THIS ERRORS
    the name "Repeater1" does not exist in the current context.
    the name "nametxt" does not exist in the current context.
    the name "emailtxt" does not exist in the current context.
    the name "content" does not exist in the current context.

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. Anoop, do you know how to make an admin Panel or an Administration Page in asp.Net. if So i will be glad if you can guide me. Thx

    ReplyDelete

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Subscribe us on YouTube

Like us on Facebook

Follow us on Google+