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"> </td>
<td class="auto-style2">
<asp:Button ID="btn_Submit"
runat="server" Text="Post Comment"
OnClick="btn_Submit_Click" CssClass="buttonSubmit"
/>
</td>
<td> </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> (<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>
|
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();
}
}
|
Hope you like it. If you have any query comment it below. Thanks.
[Download Source Code via Google Drive]
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
ReplyDeleteif you dont mind , i can help you out ......
Deletejust make one function and bind gridview in that function.. and provide
the name of that function on the submit buttton click , at the end .
how to create facebook like comment
DeleteThis comment has been removed by the author.
ReplyDeletetnx
ReplyDeleteThis comment has been removed by a blog administrator.
DeleteSir after using these codes i got error
ReplyDelete.
.
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?
sir my previous problem is solved .. but now i get this error:-
ReplyDeleteCannot 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
you need to provide "auto generate id" functionality to ur Id column as it is primary key.
Deletebecause you are not providing any value to Id, it is showing error as it cannot be left null.
HELP ME PLEASE I HAVE THIS ERRORS
ReplyDeletethe 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.
same here this error........
DeleteThis comment has been removed by the author.
ReplyDeleteAnoop, 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
ReplyDeleteNice....
ReplyDeletehow to add reply option on this code...........
ThanK You
ReplyDeleteGreat 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.
ReplyDeleteI ned the code in vb.net
ReplyDeleteI ned the code in vb.net
ReplyDeleteThank you...But my posted comments are not displaying.
ReplyDeletePlease help me
Good Tutorials...
ReplyDeleteThanks for one marvelous posting! I enjoyed reading it; you are a great
ReplyDeleteauthor. 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
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.
ReplyDeletewebsite builder for reseller
This is a very amazing post for cheap web hosting services. in this post, you have provided all the basic information regarding.
ReplyDeleteprivate label website builder
This is genuinely an awesome read for me. I have bookmarked it and I am anticipating perusing new articles. Keep doing awesome!
ReplyDeletewhite label website builder
Thank you sir provide knowledge of the ASP training
ReplyDeletePlease continue.I hope you will continue your posting of article.
ReplyDeleteفروشگاه اينترنتی
https://www.baneh.com
goodluck
ReplyDeletecrazykrush is dating apps for iphone like tinder and this is new trending app. it is available on all mobile platform
Article très original !
ReplyDeleteBonne continuation :)
https://www.medespoir.ch
Thank you very much , this blog is wonderful !
ReplyDeleteDocteur Hichem Mahmoud
Chirurgien esthétique Tunisie
This comment has been removed by the author.
ReplyDeletesir some Could not load type 'simplecomm.Global'. error is coming in the first page itself.how to rectify that one
ReplyDeletePopular SAP Solutions
ReplyDelete1. 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.