Monday 25 April 2016

Bind Dropdown Using JQuery in Asp.Net.



First create table as given below.

CREATE TABLE [dbo].[City](
          [CityId] [int] NOT NULL,
          [CityName] [nvarchar](50) NULL,
          [StateId] [int] NULL,
 CONSTRAINT [PK_City] PRIMARY KEY CLUSTERED
(
          [CityId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Then insert some dummy values into this table.

Put dropdown control on asp.net page.

<div>
        <asp:DropDownList ID="ddlCustomers" runat="server">
        </asp:DropDownList>
</div>
Now write a code for PageBehind.
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.Web.UI.MobileControls;

public partial class Jquery_BindDropdownUsingJquery : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        PopulateDropdown();
    }
    [System.Web.Services.WebMethod]
    public static List<ListItem> PopulateDropdown()
    {
       
        String strConnString = ConfigurationManager
            .ConnectionStrings["test"].ConnectionString;
        String strQuery = "select CityId, CityName from City";

        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                List<ListItem> list = new List<ListItem>();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = strQuery;
                cmd.Connection = con;
                con.Open();

                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    list.Add(new ListItem
                    {
                        Value=dr["CityId"].ToString(),
                        Text=dr["CityName"].ToString()
                    });
                }
                con.Close();
                return list;
            }
        }
       
    }
}

Now write JQuery code to populate dropdown value.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
     <script type="text/javascript">

     $(function(){
       $.ajax({
       type:"POST",
       url: "BindDropdownUsingJquery.aspx/PopulateDropdown",
       data:'{}',
       contentType:"application/json; charset=utf-8",
       dataType:"json",
       success :function(r){
       var ddlCustomers = $("[id*=ddlCustomers]");
            ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>');
            $.each(r.d, function () {
                ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
              });
            }
         });
     });
     </script>

Please run the code and check output.

Sunday 24 April 2016

What is Generic in c#?.



Generic allow you to define type safe classes without compromising type safety, performance or productivity.

 In other word we can say that, Generic allows you to delay the specification of the datatype programming element in class or methods or delegates, until it is actually used in the program.

Generic allows class or method or delegate that can work with any data type.

Examples:-
Generic Class :-
public class GenericClass<G>
    {
        private G[] Array;
        public GenericClass(int size)
        {
            Array =new G[size + 1];
        }

        public G GetItem(int index)
        {
            return Array[index];
        }

        public void SetItem(int index, G value)
        {
            Array[index] = value;
        }
    }
class Program
    {
static  void Main(string[] args)
        {
            // for int datatype
            GenericClass<int> intGeneric = new GenericClass<int>(10);
           
            for(int i=0;i<=10;i++)
            {
                intGeneric.SetItem(i, i * 2);
            }

            for (int j = 0; j < 10; j++)
            {
               Console.WriteLine(intGeneric.GetItem(j));
            }

            // for string datatype
            GenericClass<string> strGeneric = new GenericClass<string>(10);
            for (int i = 0; i < 10; i++)
            {
                strGeneric.SetItem(i, "test" + i);
            }

            for (int j = 0; j < 10; j++)
            {
                Console.WriteLine(strGeneric.GetItem(j));
            }
         }
}

Generic Method :-
 
class Program:Factory
    {
        static void Swap<T>(ref T t1, ref T t2)
        {
            T temp;
            temp = t1;
            t1 = t2;
            t2 = temp;
        }
static  void Main(string[] args)
        {
            int a = 2; int b = 5;
            Swap<int>(ref a, ref b);
            //a and b value after swap
            Console.WriteLine("{0}-{1}", a, b);

            char c, d;
            c = 'a';
            d = 'b';
            Swap<char>(ref c, ref d);
            //c and d value after swap
            Console.WriteLine("{0}-{1}", c, d);
                }
}