Forms Authentication in ASP.NET 2.0 is technique to decide how users can access your web application.
Using froms authentication we can decide certain users can access only certain pages or we can control the anonymous access, we can implement folder level access and access based on roles
we can manage the access through web.config file
Read my article on implementing forms authentication using FormsAuthentication ticket and managing roles
1. First of all create a new website and add a new form , name it Login.aspx
Drag login control on it from the toolbox
Make sure you have a web.config file in root of your application
2. Right click on solution explorer and add new folder , name it membersArea
Add a new from and name it members.aspx
Add a web.config file in this folder.
Now to implement Forms Authentication we need to configure web.config file (in the application root)
For this we need to add Authentication and Authorization tags inside <system.web> tag of web.config
<authentication mode="Forms">
<forms defaultUrl="Default.aspx" loginUrl="~/Login.aspx"
slidingExpiration="true" timeout="20">
</forms>
</authentication>
</system.web>
Now To restrict access to the membersonly page which is inside membersonly folder so that only members can access this page we need to create a another web.config file inside this folder to provide it's access rules
In this web.config write this inside <system.web> tag
<authorization>
<deny users="?"/>
</authorization>
</system.web>
Now for login process and checking the username and password we need to write this code, double click on the login control placed on the Login.aspx page, it will generate Login1_Authenticate event
protected void Login1_Authenticate
(object sender, AuthenticateEventArgs e)
{
bool isMember = AuthenticateUser(Login1.UserName, Login1.Password,
Login1.RememberMeSet);
if (isMember)
{
FormsAuthentication.RedirectFromLoginPage(Login1.UserName,
Login1.RememberMeSet);
}
}
And this for checking username and password, i m using hard coded values
{
string userName = "amiT";
string password = "password";
if (userName.Equals(userName) && password.Equals(password))
{
return true;
}
else
{
return false;
}
}
Forms Authentication In Asp.Net 2.0 3.5
Export paging enabled GridView to pdf using iTextSharp
In my previous post Export GridView to pdf using iTextSharp in ASP.NET , i explained how to write Grid View contents to a PDF file , but this code has some bugs
1. Code doesn't work if paging is enabled in GridView
2. Columns become of variable width in PDF documnt as shown in the image below
To fix these problems we need to write code without using xmlTextReader and HtmlParser.
for this we need to create a table in PDF document and then fill the cells of table from GridView
And the new html and codebehind would become like this
<%@ Page Language="C#" AutoEventWireup="true"CodeFile="Default.aspx.cs"
Inherits="_Default" %><!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
><head runat="server"><title>Untitled Page</title>
</head><body><form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1"
runat="server"AutoGenerateColumns="False"AllowPaging="true"
PageSize="5"DataSourceID="SqlDataSource1"><
Columns><asp:BoundField DataField="Name
"HeaderText="Name"SortExpression="Name" />
<asp:BoundField DataField="Location"HeaderText="Location"
SortExpression="Location" /></Columns></asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1"runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>
"SelectCommand="SELECT [Name], [Location] FROM [Test]">
</asp:SqlDataSource></div><br />
<asp:Button ID="btnExport" runat="server"
OnClick="btnExport_Click"Text="Export to PDF" />
</form></body></html>
And the code behind goes like this
protected void btnExport_Click(object sender, EventArgs e)
{
int columnCount = GridView1.Columns.Count;
int rowCount = GridView1.Rows.Count;
int tableRows = rowCount + 3;
iTextSharp.text.Table grdTable=
new iTextSharp.text.Table(columnCount, tableRows);
grdTable.BorderWidth = 1;
grdTable.BorderColor = new Color(0, 0, 255);
grdTable.Cellpadding = 5;
grdTable.Cellspacing = 5;
Cell c1 = new Cell("Exporting paging enabled GridView to PDF example");
c1.Header = true;c1.Colspan = 2;
grdTable.AddCell(c1);
Cell c2 = new Cell("By amiT jaiN , amit_jain_online@yahoo.com");
c2.Colspan = 2;
grdTable.AddCell(c2);
grdTable.AddCell("Name");
grdTable.AddCell("Location");
for (int rowCounter = 0;
rowCounter < rowCount; rowCounter++)
{for (int columnCounter = 0;columnCounter < columnCount; columnCounter++)
{string strValue =GridView1.Rows[rowCounter].Cells[columnCounter].Text;
grdTable.AddCell(strValue);
}
}
Document Doc = new Document();
PdfWriter.GetInstance(Doc, Response.OutputStream);
Doc.Open();Doc.Add(grdTable);
Doc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader
("content-disposition", "attachment; filename=AmitJain.pdf");
Response.End();
PDF created would be like this
Download the Sample code attached

Ajax AutoCompleteExtender in GridView
In this example i am implementing the AutoComplete functionality to textbox in the EditItemTemaplate of GridView using AJAX autocomplete extender, for this we need to create a web service which calls the method to fetch data from database and display results as suggestions for textbox
If you are looking for Autocomplete textbox in winforms/ windows forms application than read this articles
Creating winforms AutoComplete TextBox using C# in Windows application
For this add a new webservice to the project and name it AutoComplete.asmx or whatever you want, in the code behind of the web service we write methods to get the records from database and a web method called GetCompletionList which takes text entered in textbox as parameter to search database , this method gets automatically called when ever user types anything in the textbox, the code for this web service is like this
using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
[WebService]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : WebService
{
public AutoComplete()
{
}
[WebMethod]
public string[] GetCompletionList(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}
DataTable dt = GetRecords(prefixText);
List<string> items = new List<string>(count);
for (int i = 0; i < dt.Rows.Count; i++)
{
string strName = dt.Rows[i][0].ToString();
items.Add(strName);
}
return items.ToArray();
}
public DataTable GetRecords(string strName)
{
string strConn = ConfigurationManager.ConnectionStrings
["DatabaseConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("@Name", strName);
cmd.CommandText =
"Select Name from Test where Name like '%'+@Name+'%'";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
return objDs.Tables[0];
}
}
And in the html source for aspx page add a script manager and within scriptmanager tag , add ServiceReference and path to asmx file, in gridview add autocomplete extender for the textbox which we want to autocomplete
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1"
runat="server">
<Services>
<asp:ServiceReference Path="AutoComplete.asmx" />
</Services>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="ID"
SortExpression="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server"
Text='<%#Eval("ID") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblID" runat="server"
Text='<%#Bind("ID") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name"
SortExpression="Name">
<ItemTemplate>
<asp:Label ID = "lblName" runat="server"
Text='<%#Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server"
Text='<%#Bind("Name") %>' >
</asp:TextBox>
<ajaxToolkit:AutoCompleteExtender
runat="server"
ID="autoComplete1"
TargetControlID="txtName"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="true"
CompletionSetCount="12" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location"
SortExpression="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server"
Text='<%#Eval("Location") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblLocation" runat="server"
Text='<%#Bind("Location") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ConnectionStrings:DatabaseConnectionString%>"
SelectCommand="SELECT [ID], [Name], [Location] FROM [Test]"
UpdateCommand="Update Test set [Name] = @Name where ID = @ID">
<UpdateParameters>
<asp:Parameter Name="Name" />
<asp:Parameter Name="ID" />
</UpdateParameters>
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
Download the sample code

Disable copy paste right click using javascript in asp.net textbox
Some time for many reasons we don't want to allow user to use right click to copy paste or by using ctrl+C , ctrl+v to copy and paste in textbox on a aspx page in asp.net
To implement this we can use javascript
we can achieve this in 2 ways
1. use this method when u don't want any alerts or message
<asp:TextBox ID="TextBox1" runat="server"
oncopy="return false"
onpaste="return false"
oncut="return false">
</asp:TextBox>
2. If you want to show alerts than use this method instead
Right this javascript function in the head section of aspx page, in this function we are disabling right mouse click and ctrl keys
<head runat="server">
<title>Untitled Page</title>
<script language="javascript">
function DisableRightClick(event)
{
//For mouse right click
if (event.button==2)
{
alert("Right Clicking not allowed!");
}
}
function DisableCtrlKey(e)
{
var code = (document.all) ? event.keyCode:e.which;
var message = "Ctrl key functionality is disabled!";
// look for CTRL key press
if (parseInt(code)==17)
{
alert(message);
window.event.returnValue = false;
}
}
</script>
</head>
Now use this function on the textbox which we want to disable copy paste and right clicking
<body>
<form id="form1" runat="server">
<div>
<strong>
Right click disabled</strong> textbox
<br />
<asp:TextBox ID="TextBoxCopy" runat="server"
onMouseDown="DisableRightClick(event)">
</asp:TextBox><br />
<br />
<strong>Ctrl key </strong>disabled<br />
<asp:TextBox ID="TextBox2" runat="server"
onKeyDown="return DisableCtrlKey(event)">
</asp:TextBox><br />
<br />
Another method to disable<strong> Cut,Copy and paste
</strong>in textbox<br />
<br />
<asp:TextBox ID="TextBox1" runat="server"
oncopy="return false"
onpaste="return false"
oncut="return false">
</asp:TextBox>
</form>
</body>
Hope this helps
amiT jaiN - home for asp.net and c#.net articles and code examples with ajax and other ms technologies
Hi all ,
I am amiT jaiN , hails from of Agra , the city of Taj mahal , working in Delhi(NCR) region.
I work on Microsoft .NET platfrom , using C# .NET, ASP.NET, SQL Server, AJAX ,JavaScript, etc to develop web based applications and windows based applications
If u wanna contact me than leave me a comment here
AutoComplete TextBox In WinForms Windows Forms Application
Creating AutoComplete TextBox In WinForms Windows Forms Application Using C# VB.NET
In this example i am explaining how to create a AutoComplete TextBox In windows forms application using C#.
If you are looking for Autocomplete textbox in ASP.NET web/ aspx pages than read this article
Ajax autocomplete extender textbox in EditItemTemaplate of GridView
There are two ways we can use Autocomplete feature
1. Auto complete textBox with previously entered text in textbox.
2. AutoComplete textBox by fetching the data from database.
1. Auto complete textBox with previously entered text in textbox.
For filling textbox with previously entered data/text in textbox using Autocomplete feature we can implement by setting autocomplete mode proeprty of textbox to suggest, append or sugestappend and setting autocomplete source to custom source progrmetically
First of all create a global AutoCompleteStringCollection and write code like this
{
public partial class Form1 : Form
{
AutoCompleteStringCollection autoComplete = new AutoCompleteStringCollection();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
autoComplete.Add(textBox1.Text);
MessageBox.Show("hello");
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
//auto.Add(textBox1.Text);
textBox1.AutoCompleteCustomSource = autoComplete;
}
}
}
2. AutoComplete textBox by fetching the data from database.
For this i've created a database with a table containing names which will be shown in textbox as suggestions, for this we need to create a AutoCompleteStringCollection and then add the records in this collection using datareader to fetch records from database
For autocomplete functionalty to work we need to define these 3 properties of textbox
1. AutoCompleteMode - we can choose either suggest or appned or suggestappend as names are self explanatory
2. AutoCompleteSource - this needs to be set as Custom Source
3. AutoCompleteCustomSource - this is the collection we created earlier
The complete C# code will look like this
namespace AutoCompleteTextBox
{
public partial class frmAuto : Form
{
public string strConnection =
ConfigurationManager.AppSettings["ConnString"];
AutoCompleteStringCollection namesCollection =
new AutoCompleteStringCollection();
public frmAuto()
{
InitializeComponent();
}
private void frmAuto_Load(object sender, EventArgs e)
{
SqlDataReader dReader;
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strConnection;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"Select distinct [Name] from [Names]" +
" order by [Name] asc";
conn.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
namesCollection.Add(dReader["Name"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close();
txtName.AutoCompleteMode = AutoCompleteMode.Suggest;
txtName.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtName.AutoCompleteCustomSource = namesCollection;
}
private void btnCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnOk_Click(object sender, EventArgs e)
{
MessageBox.Show("Hope you like this example");
}
}
}
In the similar way we can also create a autocomplete type combobox
Download Sample code attached

amiT jaiN - Welcome to world of ASP.NET C#.NET csharp.net articles and code exampls
Hi all , If u wanna contact me than leave me a comment here
i am amiT jaiN , hails from of Agra , the city of Taj mahal , working in Delhi(NCR) region.
I work on Microsoft .NET platfrom , using C# .NET, ASP.NET, SQL Server, AJAX ,JavaScript, etc
to develop web based applications and windows based applications
Tags
Blog Archive
-
►
2012
(11)
-
►
January
(11)
- Download File From Server In Asp.Net
- AspNet CompareValidator With Date Example
- Create User Registration Form In AspNet
- Visual Studio Remove Unused References With Organi...
- Get RowIndex In GridView RowCommand Event Using Da...
- Save Store Files In SqlServer Database AspNet
- Nested GridView In Asp.Net Or GridView Inside Grid...
- Add License Agreement In Visual Studio Setup Proje...
- Ajax Asp.Net PasswordStrength Example
- Invalid Formatetc Structure Ajax Asp.Net Error
- Create User Programmatically Using Membership In A...
-
►
January
(11)
-
►
2011
(46)
-
►
December
(13)
- CreateUserWizard Email Verification Or Confirmatio...
- Login Page Example Using Login Control In Asp.Net
- Set Session TimeOut In Asp.Net Using WebConfig IIS...
- Remove Delete Duplicate Rows/Records From DataTabl...
- DropDownList In DetailsView EditItemTemplate
- A Potentially Dangerous Request.Form Value Was Det...
- Write Modify Web.Config Programmatically At Run Ti...
- GridView XML Edit Delete Insert Update
- Upload And Read Excel File In Asp.Net
- VisualStudio SetupProject Updates Version Already ...
- Read CSV File And Save To SQL Server In ASP.NET C#...
- GridView XMLDataSource Example
- Add Controls Dynamically WinForms WindowsFroms C# ...
-
►
December
(13)
-
▼
2009
(62)
-
▼
January
(7)
- Forms Authentication In Asp.Net 2.0 3.5
- Export paging enabled GridView to pdf using iTextS...
- Ajax AutoCompleteExtender in GridView
- Disable copy paste right click using javascript in...
- amiT jaiN - home for asp.net and c#.net articles a...
- AutoComplete TextBox In WinForms Windows Forms App...
- amiT jaiN - Welcome to world of ASP.NET C#.NET csh...
-
▼
January
(7)
Topics
- AJAX
- AppFabric
- ASP.NET
- Authentication
- AutoComplete Extender
- Blogger Tricks
- BloggerTips
- C#
- Cookies
- Cross Page Posting
- Crystal Reports
- DataKeyNames
- DataList
- DetailsView
- DropDownList
- EditItemTemplate
- Excel
- FileUpload
- FindControl
- FooterTemplate
- Forms Authentication
- GridView
- IIS
- ItemTemplate
- iTextSharp
- JavaScript
- jQuery
- LoginControl
- MembershipProvider
- ModalPopUpExtender
- ObjectDataSource
- Performance Optimization
- Progress Template
- QueryString
- Server.Transfer
- Session
- Sql Server
- Submit Form
- TraceMobileNumber
- Update Panel
- VB.NET
- Visual studio
- Web Service
- Web.config
- Windows Froms
- WinForms
- XML
Popular Posts
-
Trace Mobile Number in India with Location and Operator Several times we feel the need to trace or track any mobile phone number , it's...
-
Trace mobile number in india Enter phone number in textbox and Use the trace button below to trace mobile phone number in india. You...
-
In this example i'm going to describe how to implement Ajax Modal PopUp Extender on Mouse Over in ASP.NET using C# and VB.NET For this to ...
-
In this example i m going to describe how to create crystal reports in ASP.NET. In this i am generating report by fetching data from two t...
-
In this example i am going to describe how to Insert record or edit or delete record in GridView using SqlDataSource. For inserting record...
