Thursday, 25 July 2013

Palindrome program in c#.net.

In this Article , I have explained palindrome program in c#. This program is generally asked in interview.

What is palindrome.

Answer:- Palindrome means when you reverse the string or number then the reversed string or number is equal to original string or number.

Program:-


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Consoleprogram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the string");
            Program pgrm = new Program();
            string a=Console.ReadLine();
            pgrm.palindrom(a);
            Console.ReadKey();
        }
        public string palindrom(string str)
        {
            //str = Console.ReadLine();
            string s=string.Empty;
            int strLenght = str.Length;
            for (int i = strLenght-1; i >=0; i--)
            {
                s = s + str[i];
            }
            if (s == str)
            {
                Console.WriteLine("Entered string is Palindrom.");
            }
            else
            {
                Console.WriteLine("Entered String is not palindrom.");
            }
            return str;
        }
    }

}

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();
    }
}