Wednesday 5 June 2013

Auto complete TextBox in asp.net using JQuery.

Introduction:-

In this article , I have explained Auto complete textbox in asp.net using Jquery.

DataBase:-

Create table  Customers(CustomerId int,ContactName varchar(max);

Insert some dummy data in this table.

Open Visual studio -> create new website.

Add one web service file in this project.

WebService.cs:-

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Script.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
 [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat=ResponseFormat.Json)]
    public string[] GetCustomer(string prefix)
    {
        List<string> customer = new List<string>();
        using (SqlConnection con = new SqlConnection())
        {
            con.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "Select CustomerId,ContactName from Customers where " + "ContactName like @SearchText +'%'";
                cmd.Parameters.AddWithValue("@SearchText", prefix);
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        customer.Add(string.Format("{0}-{1}", dr["ContactName"], dr["CustomerId"]));
                    }
                }
                con.Close();
            }
            return customer.ToArray();
        }
    }
   
}

Design Page:-

Put one textbox on design page.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:HiddenField ID="hfCustomerid" runat="server" />
Jquery Code:-
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"
type = "text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
type = "text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel = "Stylesheet" type="text/css" />
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=TextBox1.ClientID %>").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/WebService.asmx/GetCustomer") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $("#<%=hfCustomerid.ClientID %>").val(i.item.val);
            },
            minLength: 1
        });
    });
</script>

Fullcode:-

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"
type = "text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
type = "text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel = "Stylesheet" type="text/css" />
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=TextBox1.ClientID %>").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/WebService.asmx/GetCustomer") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $("#<%=hfCustomerid.ClientID %>").val(i.item.val);
            },
            minLength: 1
        });
    });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:HiddenField ID="hfCustomerid" runat="server" />
    </div>
    </form>
</body>
</html>


How to bind DropDownList in GridView Footer Template in asp.net using c#.

Introdcution:-

In this article , I have explained how to bind dropdownlist in gridview footer template (footer row) in asp.net using c#. For Binding a Footer template (footer row) ,first you have to find dropdown in gridview using FindControl.

DataBase:-

Create table  Customers(ContactName varchar(max),City varchar(200),Country varchar(50));
Insert some dummy data in this table.

Design page:-

Drag and drop GridView Control on design page and customize the gridview like below.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="true">
        <Columns>
        <asp:TemplateField>
        <FooterTemplate>
            <asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" />
        </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name">
        <ItemTemplate>
            <asp:Label ID="Label1" runat="server" Text='<%#Eval("ContactName") %>'></asp:Label>
        </ItemTemplate>
        <FooterTemplate>
            <asp:TextBox ID="txtname" runat="server" Width="150px"></asp:TextBox>
        </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="City">
        <ItemTemplate>
            <asp:Label ID="Label1" runat="server" Text='<%#Eval("City") %>'></asp:Label>
        </ItemTemplate>
        <FooterTemplate>
            <asp:DropDownList ID="ddcity" runat="server" Width="150px">
            </asp:DropDownList>
        </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Country">
        <ItemTemplate>
            <asp:Label ID="Label1" runat="server" Text='<%#Eval("Country") %>'></asp:Label>
        </ItemTemplate>
        <FooterTemplate>
            <asp:DropDownList ID="ddcountry" runat="server" Width="150px">
            </asp:DropDownList>
        </FooterTemplate>
        </asp:TemplateField>
        </Columns>
        </asp:GridView>

Code Behind Page:-
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class BindGridViewFooterColumn : System.Web.UI.Page
{
    string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    SqlConnection con;
    SqlCommand cmd;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            GridBind();
            BindCountry();
            BindCity();
        }
    }
    public void GridBind()
    {
        GridView1.DataSource = GetData("Select ContactName,City,Country from Customers");
        GridView1.DataBind();
       
    }
    public void BindCountry()
    {
        DropDownList ddcountry =(DropDownList)GridView1.FooterRow.FindControl("ddcountry");
        ddcountry.DataSource = GetData("Select DISTINCT Country from Customers");
        ddcountry.DataTextField = "Country";
        ddcountry.DataValueField = "Country";
        ddcountry.DataBind();
        ddcountry.Items.Insert(0, new ListItem("Select", "0"));
    }
    public void BindCity()
    {
        DropDownList ddcity = (DropDownList)GridView1.FooterRow.FindControl("ddcity");
        ddcity.DataSource = GetData("Select DISTINCT City from Customers");
        ddcity.DataTextField = "City";
        ddcity.DataValueField = "City";
        ddcity.DataBind();
        ddcity.Items.Insert(0, new ListItem("Select", "0"));
    }
    public DataTable GetData(string query)
    {
        using (con = new SqlConnection(constring))
        {
            using (cmd = new SqlCommand())
            {
                cmd.CommandText = query;
                using (SqlDataAdapter da = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    da.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        da.Fill(dt);
                        return dt;
                    }
                }
            }
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        TextBox  name=(TextBox)GridView1.FooterRow.FindControl("txtname");
        DropDownList city = (DropDownList)GridView1.FooterRow.FindControl("ddcity");
        DropDownList country = (DropDownList)GridView1.FooterRow.FindControl("ddcountry");
        con = new SqlConnection(constring);
        con.Open();
        cmd = new SqlCommand("Insert into Customers(ContactName,City,Country) values('"+name.Text+"','"+city.Text+"','"+country.Text+"')", con);
        cmd.ExecuteNonQuery();
        con.Close();
        GridBind();
    }
}


Tuesday 4 June 2013

How to generate Random password in asp.net using c#.

Introduction:-

In this article , I have explained how to generate random password in asp.net using c#. This is very simple to generate random password using Random function of c#. You are thinking what is need to generate random password . You have seen in many website when you register in website they have asked to enter your email_id  and then after they send user name and password in your email because it is tuff work to generate password manully.

Now open Visual studio -> open new website .

On design page put three labels.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Mixed Pass: <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
        Lower Pass: <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br />
        Upper Pass: <asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
</html>

Code behind page:-

protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = LowerOrUpperCasePassGen();
        Label2.Text = LowerCasePass();
        Label3.Text = UpperCasePass();
    }
    protected  Random ran = new Random();
    protected string[] strCharacters = { "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
                                                           "1","2","3","4","5","6","7","8","9","0",
                                                           "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
    // mixed pass gen or combination with lower and uppercase
    public string LowerOrUpperCasePassGen()
    {
        int p = 0;
        string pass = string.Empty;
        Random ran = new Random();
        for (int x = 0; x < 8; x++)
        {
            p = ran.Next(0, 61);
            pass += strCharacters[p];
        }
        return pass;
    }
    //for only Upper case pass gen.
    public string UpperCasePass()
    {
        int p = 0;
        string pass = string.Empty;
        Random ran = new Random();
        for (int x = 0; x < 8; x++)
        {
            p = ran.Next(0, 35);
            pass += strCharacters[p];
        }
        return pass;
    }
    //for only lower case pass gen.
    public string LowerCasePass()
    {
        int p = 0;
        string pass = string.Empty;
        Random ran = new Random();
        for (int x = 0; x < 8; x++)
        {
            p = ran.Next(26, 61);
            pass += strCharacters[p];
        }
        return pass;
    }


In this code you can generate random password for 8 character or digit or mixed. If You want to generate random password greater than 8 then change the digit in for loop.