70

Failed to access IIS metabase ASP.NET

Failed To Access IIS Metabase Error In ASP.NET, If You are getting "Failed to access IIS metabase" error while browsing asp.net site or aspx page in IIS server then you may have installed IIS Server after installing the .NET framework.

If that's the case, try running to repair your ASP.NET installation and set up all of the appropriate ISAPI extension mappings.

Open visual studio command prompt and type this command

aspnet_regiis -ga \username
username is usually aspnet


if this doesn't work than use this command
aspnet_regiis -i

alternatively you can copy and paste this command into windows command prompt

%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i

this will fix your problem



18

Forms Authentication Ticket In Asp.Net 2.0 3.5

In this article i am explaining how to implement FormsAuthenticationTicket And Managing UserData Roles In Asp.Net 2.0,3.5,4.0 using C# And VB.NET



For implementing forms authentication without using formsauthentication ticket, read my previous article - Forms Authentication with C# and managing folder lavel access with multiple web.config files

Configuring web.config file in application root


<authentication mode="Forms">
<forms defaultUrl="Default.aspx" loginUrl="~/Login.aspx"
slidingExpiration="true" timeout="20"></forms>
</authentication>

Defining roles and accessibility in root web.config

<location path="Admin">
<system.web>
<authorization>
<allow roles="admin"/>
<deny users="*"/>
</authorization>

</system.web>

</location>


Defining roles settings for folders and aspx within those folders in web.config file in those folders

<system.web>
<authorization>
<allow roles="user"/>
<deny users="*"/>
</authorization>
</system.web>

settings for any logged in member

<system.web>
<authorization>
<deny users="?"/>
</authorization>


Now after creating Login page we need to authenticate user

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string userName = Login1.UserName;
string password = Login1.Password;
bool rememberUserName = Login1.RememberMeSet;

//Fetch User login information fromthe xml file into Dataset

string xmlFilePath = Server.MapPath("~/App_Data/LoginInfo.xml");
DataSet objDs = new DataSet();
objDs.ReadXml(xmlFilePath);
DataRow[] dRow = objDs.Tables[0].Select("UserName = '" + userName + "' and Password = '" + password + "'");
if (dRow.Length > 0)
{
//Fetch the role
string roles = dRow[0]["Roles"].ToString();

//Create Form Authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(20), rememberUserName, roles, FormsAuthentication.FormsCookiePath);

// In the above parameters 1 is ticket version, username is the username associated with this ticket
//time when ticket was issued , time when ticket will expire, remember username is user has chekced it
//roles associted with the user, and path of cookie if any

//For security reasons we may hash the cookies
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);

// add the cookie to user browser

Response.Cookies.Add(cookie);

// get the requested page

string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null)
returnUrl = "~/Default.aspx";
Response.Redirect(returnUrl);
}


Now to retrieve the authentication and roles information on every request we need to write this code in Global.asax file

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
// look if any security information exists for this request

if (HttpContext.Current.User != null)
{

// see if this user is authenticated, any authenticated cookie (ticket) exists for this user

if (HttpContext.Current.User.Identity.IsAuthenticated)
{

// see if the authentication is done using FormsAuthentication

if (HttpContext.Current.User.Identity is FormsIdentity)
{

// Get the roles stored for this request from the ticket

// get the identity of the user

FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;

//Get the form authentication ticket of the user

FormsAuthenticationTicket ticket = identity.Ticket;

//Get the roles stored as UserData into ticket

string[] roles = ticket.UserData.Split(',');

//Create general prrincipal and assign it to current request

HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
}
}
}
}


To check whether user in in the role or not we need to write this code in every page which provide access on role basis

protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.IsInRole("admin"))
{
lblMessage.Text = "Welcome Administrator";
}
}


Download sample code


Related Articles :

1. Forms Authentication with C# and managing
folder lavel access with multiple web.config files


2. User validation across pages using session
after login in ASP.NET using C sharp


3. Detecting Session Timeout
and Redirect to Login Page in ASP.NET

27

Ajax Cascading DropDownList With Database Example in GridView

This example implements Ajax Cascading DropDownList With Database In GridView Using Asp.Net 2.0,3.5,4.0. There are several cases when you have two or three dropdowns in gridview and want second one (and third one) to be populated based on selection of first or second dropdownlist.

I've used Ajax cascading dropdownlist in EditItemTemaplete of GridView for updation of records in grid by fetching data from database to populate dropdowns,I've also implemented ajax auto complete extender textbox in it to edit name field

Make sure you have created ajax enabled website and installed ajax toolkit and ajax web extensions properly

Gridview displays Name, City, and Country on page load,



City and Country field turns into cascading dropdown list when user clicks on Edit link


Ajax cascading dropdown extender uses webservice to fetch data from database and populate dropdowns, city dropdown is populated based on country selected in country dropdown

Important points to remember

1. Put AjaxControlToolkit.dll in bin folder of your application.
2. Set EventValidation to false in page directive of your aspx page

<%@ Page Language="C#" EnableEventValidation="false"
AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>

Here is explanation why you need to turn it off ?
in order for the values to be submitted, EventValidation needs to be disabled for the page. EventValidation ensures that the values in each control match the values that were present when the page was rendered, but since these drop downs are populating on the client side, this is never true.

3. If you are getting Error method 500 or 12031 than read this to resolve this error

4. Webservice must have the webmethod with following signature and exact parameters
[WebMethod]
public CascadingDropDownNameValue[] GetColorsForModel(
string knownCategoryValues,
string category)

You can change the method name but return type must be CascadingDropDownNameValue[] with knownCategoryValues,category as parameters

First of all add a new webservice and name it CascadingDropDown.asmx
In code behind of this asmx file write following code
Add these namespaces
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using AjaxControlToolkit;
using System.Collections.Specialized;

/// <summary>
/// Summary description for CascadingDropDown
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class CascadingDropDown : System.Web.Services.WebService
{
//Create global Connection string
string strConnection = ConfigurationManager.ConnectionStrings
["dbConnectionString"].ConnectionString;

public CascadingDropDown () {

//Uncomment the following line if using designed components 
//InitializeComponent(); 
}
/// <summary>
/// WebMethod to populate country Dropdown
/// </summary>
/// <param name="knownCategoryValues"></param>
/// <param name="category"></param>
/// <returns>countrynames</returns>
[WebMethod]
public CascadingDropDownNameValue[] GetCountries
(string knownCategoryValues, string category)
{
//Create sql connection and sql command
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "Select * from Country";

//Create dataadapter and fill the dataset
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
con.Close();

//create list and add items in it 
//by looping through dataset table
List<CascadingDropDownNameValue> countryNames
= new List<CascadingDropDownNameValue>();
foreach (DataRow dRow in objDs.Tables[0].Rows)
{
string countryID = dRow["CountryID"].ToString();
string countryName = dRow["CountryName"].ToString();
countryNames.Add(new CascadingDropDownNameValue
(countryName, countryID));
}
return countryNames.ToArray();


}

[WebMethod]
public CascadingDropDownNameValue[] GetCities
(string knownCategoryValues, string category)
{
int countryID;
//this stringdictionary contains has table with key value
//pair of cooountry and countryID
StringDictionary countryValues =
AjaxControlToolkit.CascadingDropDown.
ParseKnownCategoryValuesString(knownCategoryValues);
countryID = Convert.ToInt32(countryValues["Country"]);

SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("@CountryID", countryID);
cmd.CommandText =
"Select * from City where CountryID = @CountryID";

SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
con.Close();
List<CascadingDropDownNameValue> cityNames =
new List<CascadingDropDownNameValue>();
foreach (DataRow dRow in objDs.Tables[0].Rows)
{
string cityID = dRow["CityID"].ToString();
string cityName = dRow["CityName"].ToString();
cityNames.Add(new CascadingDropDownNameValue
(cityName, cityID));
}
return cityNames.ToArray();
}

}


Now in html source of aspx page I've put two dropdowns in EditItemTemaplate of gridview
<EditItemTemplate>
<asp:DropDownList ID="ddlCountry" runat="server">
</asp:DropDownList><br />
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown1"
runat="server"
Category="Country"
TargetControlID="ddlCountry"
PromptText="-Select Country-"
LoadingText="Loading Countries.."
ServicePath="CascadingDropDown.asmx"
ServiceMethod="GetCountries">
</ajaxToolkit:CascadingDropDown>
</EditItemTemplate>


Here TargetControlID is id of dropdown on which cascading dropdown is to be implemented ,Service path is path to webservice and ServiceMethod is method to fetch the data from databse and populate dropdown

You also need to add reference to webservive in script manager
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="CascadingDropDown.asmx" />
</Services>
</asp:ScriptManager>


The complete html source is like this
<%@ Page Language="C#" EnableEventValidation="false"
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" />
<asp:ServiceReference Path="CascadingDropDown.asmx" />
</Services>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
OnRowUpdating="GridView1_RowUpdating">

<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="Country"
SortExpression="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server"
Text='<%#Eval("Country") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCountry" runat="server">
</asp:DropDownList>
<ajaxToolkit:CascadingDropDown
ID="CascadingDropDown1"
runat="server"
Category="Country"
TargetControlID="ddlCountry"
PromptText="-Select Country-"
LoadingText="Loading Countries.."
ServicePath="CascadingDropDown.asmx"
ServiceMethod="GetCountries">
</ajaxToolkit:CascadingDropDown>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="City"
SortExpression="City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server"
Text='<%#Eval("City") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCity" runat="server"
OnSelectedIndexChanged="ddlCity_SelectedIndexChanged">
</asp:DropDownList><br />
<ajaxToolkit:CascadingDropDown
ID="CascadingDropDown2"
runat="server"
Category="City"
TargetControlID="ddlCity"
ParentControlID="ddlCountry"
PromptText="-Select City-"
LoadingText="Loading Cities.."
ServicePath="CascadingDropDown.asmx"
ServiceMethod="GetCities">
</ajaxToolkit:CascadingDropDown>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<div>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:dbConnectionString %>"
SelectCommand="SELECT [ID], [Name], [City],[Country]
FROM [Location]"
UpdateCommand="Update Location set [Name] = @Name,
[City] = @City,[Country] = @Country
where ID = @ID">
<UpdateParameters>
<asp:Parameter Name="Name" />
<asp:Parameter Name="ID" />
<asp:Parameter Name="Country"/>
<asp:Parameter Name="City"/>
</UpdateParameters>
</asp:SqlDataSource>

</div>
</form> 
</body>
</html>


Finally write this code in code behind of aspx page to update record
protected void GridView1_RowUpdating
(object sender, GridViewUpdateEventArgs e)
{
//Find dropdown to get selected Item text  
DropDownList ddlGridCountry = (DropDownList)
GridView1.Rows[e.RowIndex].FindControl("ddlCountry");
string strCountry =
ddlGridCountry.SelectedItem.Text.ToString();

DropDownList ddlGridCity = (DropDownList)
GridView1.Rows[e.RowIndex].FindControl("ddlCity");
string strCity =
ddlGridCity.SelectedItem.Text.ToString();

SqlDataSource1.UpdateParameters.Clear();
SqlDataSource1.UpdateParameters.Add
("Country", strCountry);
SqlDataSource1.UpdateParameters.Add("City", strCity);
}


Hope this helps

I wrote similar article in case you don't use ajax , than u can go through this

1. C#.NET Articles -Cascading DropDownList Populate dropdown based on selection of other dropdown in ASP.NET

2. Populating dropdown based on the selection of first drop down in DetailsView using FindControl and ItemTemplate

Download the sample code attached

9

Forms Authentication In Asp.Net 2.0 3.5 4.0

Forms Authentication in ASP.NET 2.0, 3.5, 4.0 With Folder Level Access And Multiple Web.Config Files is technique to decide how users can access your web application. Using forms 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 roles.

we can manage formsAuthentication through web.config file

Read my article on implementing 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

<system.web>
<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
<system.web>
<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
private bool AuthenticateUser(string userName, string password, bool rememberUserName)
{
string userName = "amiT";
string password = "password";

if (userName.Equals(userName) && password.Equals(password))
{
return true;
}
else
{
return false;
}
}


14

Export Paging Enabled GridView To PDF Using ITextSharp

Export Paging Enabled GridView To PDF Using ITextSharp C# VB.NET In ASP.NET. In my previous post Export GridView to pdf , 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




16

Ajax AutoCompleteExtender in GridView

In this example i am implementing Ajax AutoCompleteExtender TextBox in EditItemTemaplate of GridView using AjaxControlToolkit In Asp.Net, 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

We can also create AutoComplete TextBox In Winforms Windows Forms Application.

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 records from database and a web method called GetCompletionList which takes text entered in textbox as parameter to search database , this method is automatically called when ever user types anything in the textbox, following is the code for web service.

C# CODE


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService {

    public AutoComplete () 
    {
             
    }

    [WebMethod]
    public string[] GetCompletionList(string prefixText, int count)
    {
        if (count == 0)
        {
            count = 10;
        }
        DataTable dt = GetRecords(prefixText);
        List items = new List(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];
   }
}


VB.NET
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Collections.Generic
Imports System.Data.SqlClient
Imports System.Data
Imports System.Configuration


 _
 _
 _
 _
Public Class AutoComplete
    Inherits System.Web.Services.WebService

     _
    Public Function GetCompletionList(ByVal prefixText As String, ByVal count As Integer) As String()
        If count = 0 Then
            count = 10
        End If
        Dim dt As DataTable = GetRecords(prefixText)
        Dim items As New List(Of String)(count)

        For i As Integer = 0 To dt.Rows.Count - 1
            Dim strName As String = dt.Rows(i)(0).ToString()
            items.Add(strName)
        Next
        Return items.ToArray()
    End Function

    Public Function GetRecords(ByVal strName As String) As DataTable
        Dim strConn As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString
        Dim con As New SqlConnection(strConn)
        Dim cmd As 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+'%'"
        Dim objDs As New DataSet()
        Dim dAdapter As New SqlDataAdapter()
        dAdapter.SelectCommand = cmd
        con.Open()
        dAdapter.Fill(objDs)
        con.Close()
        Return objDs.Tables(0)

    End Function

End Class


In html source of aspx page add a ToolkitScriptManager and add ServiceReference and path to asmx file inside it, in gridview add autocomplete extender for the textbox which we want to show auto suggestion.

   1:  <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
   2:  <Services>
   3:       <asp:ServiceReference Path="AutoComplete.asmx"/>
   4:  </Services>
   5:  </asp:ToolkitScriptManager>
   6:   
   7:  <asp:UpdatePanel ID="UpdatePanel1" runat="server">
   8:  <ContentTemplate>
   9:   
  10:  <asp:GridView ID="GridView1" runat="server"
  11:                AutoGenerateColumns="False"
  12:                DataSourceID="SqlDataSource1">
  13:  <Columns>
  14:  <asp:CommandField ShowEditButton="True"/>
  15:  <asp:TemplateField HeaderText="ID" SortExpression="ID">
  16:  <ItemTemplate>
  17:  <asp:Label ID="lblID" runat="server" Text='<%#Eval("ID") %>'/>
  18:  </ItemTemplate>
  19:   
  20:  <EditItemTemplate>
  21:  <asp:Label ID="lblID" runat="server" Text='<%#Bind("ID") %>'/>
  22:  </EditItemTemplate>
  23:  </asp:TemplateField>
  24:   
  25:  <asp:TemplateField HeaderText="Name" SortExpression="Name">
  26:  <ItemTemplate>
  27:  <asp:Label ID = "lblName" runat="server" Text='<%#Eval("Name")%>'/>
  28:  </ItemTemplate>
  29:  <EditItemTemplate>
  30:  <asp:TextBox ID="txtName" runat="server" Text='<%#Bind("Name")%>'/>
  31:   
  32:  <asp:AutoCompleteExtender runat="server" 
  33:                            ID="autoComplete1" 
  34:                            TargetControlID="txtName"
  35:                            ServicePath="AutoComplete.asmx" 
  36:                            ServiceMethod="GetCompletionList"
  37:                            MinimumPrefixLength="1" 
  38:                            CompletionInterval="10"
  39:                            EnableCaching="true"
  40:                            CompletionSetCount="12" />
  41:  </EditItemTemplate>
  42:  </asp:TemplateField>
  43:   
  44:  </Columns>
  45:  </asp:GridView>
  46:  </ContentTemplate>
  47:  </asp:UpdatePanel>
  48:   
  49:  <asp:SqlDataSource ID="SqlDataSource1" runat="server"
  50:  ConnectionString="<%$ConnectionStrings:DatabaseConnectionString%>"
  51:  SelectCommand="SELECT [ID], [Name] FROM [Test]"
  52:  UpdateCommand="Update Test set [Name] = @Name where ID = @ID">
  53:  <UpdateParameters>
  54:  <asp:Parameter Name="Name" />
  55:  <asp:Parameter Name="ID" />
  56:  </UpdateParameters>
  57:  </asp:SqlDataSource>


AutoComplete Extender In GridView Asp.Net


Download Sample Code


35

Disable Copy Paste Right Click Using JavaScript In Asp.Net TextBox

In this example i'm explaining how to Disable Copy Paste Right Click Using JavaScript In Asp.Net TextBox, Some time for many reasons we don't want to allow users to use right click to copy paste or by using ctrl+C , ctrl+v in textbox on a aspx page in asp.net, To disable 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


39

AutoComplete TextBox In WinForms Windows Forms Application

In this example i am explaining how to create AutoComplete TextBox In WinForms Windows Forms Application Using C# VB.NET. There are two ways we can use Autocomplete feature

1. Auto complete with previously entered text in textbox.

2. AutoComplete TextBox by fetching data from database.

Read Ajax AutoComplete Extender Textbox for asp.net web applications.

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

namespace WindowsApplication1
{
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


Find More Articles