Support us on YouTube by Subscribing our YouTube Channel. Click here to Subscribe our YouTube Channel

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]

32 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
    Replies
    1. if you dont mind , i can help you out ......

      just make one function and bind gridview in that function.. and provide
      the name of that function on the submit buttton click , at the end .

      Delete
    2. how to create facebook like comment

      Delete
  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
  9. Nice....

    how to add reply option on this code...........

    ReplyDelete
  10. Great article.I agree with your all points.Children should be treated with love and affection.Parents should be have friendly attitude and equality should be there.Thank you for sharing.

    ReplyDelete
  11. I ned the code in vb.net

    ReplyDelete
  12. I ned the code in vb.net

    ReplyDelete
  13. Thank you...But my posted comments are not displaying.
    Please help me

    ReplyDelete
  14. Thanks for one marvelous posting! I enjoyed reading it; you are a great
    author. I will make sure to bookmark your blog and may come back
    someday. I want to encourage that you continue your great posts, have
    a nice weekend!
    Visit Us: http://www.zerobugacademy.com/angularjs-training-in-chennai

    ReplyDelete
  15. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.


    website builder for reseller

    ReplyDelete
  16. This is a very amazing post for cheap web hosting services. in this post, you have provided all the basic information regarding.

    private label website builder

    ReplyDelete
  17. This is genuinely an awesome read for me. I have bookmarked it and I am anticipating perusing new articles. Keep doing awesome!

    white label website builder

    ReplyDelete
  18. Thank you sir provide knowledge of the ASP training

    ReplyDelete
  19. Please continue.I hope you will continue your posting of article.
    فروشگاه اينترنتی
    https://www.baneh.com
    goodluck

    ReplyDelete

  20. crazykrush is dating apps for iphone like tinder and this is new trending app. it is available on all mobile platform

    ReplyDelete
  21. Article très original !
    Bonne continuation :)
    https://www.medespoir.ch

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

    ReplyDelete
  23. sir some Could not load type 'simplecomm.Global'. error is coming in the first page itself.how to rectify that one

    ReplyDelete
  24. Popular SAP Solutions
    1. SAP S/4HANA
    The next-generation ERP solution from SAP, SAP S/4HANA, is built on an in-memory database and offers real-time analytics, simplified architecture, and intelligent automation.

    2. SAP Business One
    Aimed at small and medium-sized enterprises (SMEs), SAP Business One provides a cost-effective solution for managing financials, sales, and inventory.

    3. SAP SuccessFactors
    A leading human experience management (HXM) suite, SAP SuccessFactors focuses on enhancing employee engagement and optimizing workforce performance.

    4. SAP Ariba
    SAP Ariba revolutionizes procurement and supply chain management by connecting businesses with a vast network of suppliers.

    5. SAP Customer Experience (CX)
    SAP’s CX suite, formerly known as SAP C/4HANA, offers tools for customer relationship management, sales, and marketing automation.

    6. SAP Analytics Cloud
    A powerful business intelligence tool, SAP Analytics Cloud enables businesses to visualize data, create reports, and perform predictive analytics.

    ReplyDelete

Subscribe us on YouTube

Subscribe Now

Popular Posts

Contact us

Name

Email *

Message *

Like us on Facebook

Blog Archive