Pages

Wednesday, February 22, 2012

Difference between const and readonly in c#

Difference between const and readonly in c#
Following are the difference between const and readonly .
Const: 
1.const can only be initialized at the declaration of the field.
2.const is static by default.
3.Value is evaluated at compile time.
Readonly :
1.Readonly can be initialized either at the declaration or in a constructor.
2.Value is evaluated at run time.
3.Readonly fields can have different values depending on the constructor used.
Example of const and readonly keywords in c# :
class MyClass 
{
     public readonly int y = 20; // Initialize a readonly field
     public readonly int z;

     public const int c1 = 5; // Initialize a const

     public MyClass() 
     {
        z = 24;   // Initialize a readonly instance field in constructor.
     }
}

Related Other posts

Friday, February 17, 2012

Convert Datatable to generic list collection in c#

Convert Datatable to generic list collection in c#

Introduction :In this article i will show you how to convert Datatable to generic list collection in c# . It is very easy to conversion form DataTable to generic list collection .I have  showed here as step by step

Class Example
public class City
{
 public int CityId { get; set; }
 public string Cityname { get; set; }
}
C# Code Convert DataTable to generic list collection :
List<City> CityCollection = new List<City>();

DataSet Ds = GetDataSet("Select CountryID,CountryName from Countrytable");
CityCollection = Ds.Tables[0].AsEnumerable().Select(data => new City() { CityId = (int)data["CountryID"], Cityname = (string)data["CountryName"] }).ToList();

public static DataSet GetDataSet(string Query)
{
 DataSet Ds = new DataSet();
 try
 {
  string strCon = @"Data Source=ServerName;Initial Catalog=Test;Integrated Security=True";
  SqlConnection Con = new SqlConnection(strCon);
  SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
  Da.Fill(Ds);

 }
 catch (Exception) { }
 return Ds;
}


Related Other posts

bind DropDownList using jquery ajax in asp.net

Bind DropDownList using Jquery Ajax in Asp.net

Introduction : In this article i will show you how to bind a DropDownList to avoid page refresh via a webmethod .It is very useful and many time we require to use Jquery ajax . I have here provided html and c# code behind code to understand Jquery Ajax in asp.net .

Jquery Ajax Code to Bind dropdownlist in asp.net
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
 $(document).ready(function () {
  $.ajax({
   type: "POST",
   contentType: "application/json; charset=utf-8",
   data: "{}",
   url: "AjaxInJquery.aspx/GetCityData",
   dataType: "json",
   success: ajaxSucceess,
   error: ajaxError
  });
  function ajaxSucceess(response) {
   $.each(response.d, function (key, value) {
    $("#ddlCategory").append($("<option></option>").val(value.CityId).html(value.Cityname));
   });
  }
  function ajaxError(response) {
   alert(response.status + ' ' + response.statusText);
  }
 });
</script>
Html Code DropDownList
<asp:DropDownList ID="ddlCategory" runat="server">
</asp:DropDownList>
C# Code for binding Dropdownlist using Jquery Ajax
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Services;
using System.Data.SqlClient;

public partial class AjaxInJquery : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {

 }
 [WebMethod]
 public static List GetCityData()
 {
  List CityCollection = new List();
  try
  {
   DataSet Ds = GetDataSet("Select * from Countrytable");
   CityCollection = Ds.Tables[0].AsEnumerable().Select(data => new City() { CityId = (int)data["CountryID"], Cityname = (string)data["CountryName"] }).ToList();

  }
  catch (Exception) { }
  return CityCollection;
 }
 public static DataSet GetDataSet(string Query)
 {
  DataSet Ds = new DataSet();
  try
  {
   string strCon = @"Data Source=ServerName;Initial Catalog=Test;Integrated Security=True";
   SqlConnection Con = new SqlConnection(strCon);
   SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
   Da.Fill(Ds);

  }
  catch (Exception) { }
  return Ds;
 }
}
public class City
{
 public int CityId { get; set; }
 public string Cityname { get; set; }
}

Related Other posts

Thursday, February 9, 2012

Order By Class List<> in C#

Order by Ascending and Descending class List<> in C# :

Introduction : In this article i will explain you how to sort class collection ( List<> of class ) in linq c# . I done the easy code to understand how to uses Order by Ascending and Descending of class list in linq c#.

Class example for sorting class List<> In c#: Following is the user class example with constructor in c#.
public class User
{
    public int UserId { get; set; }
    public string Firstname { get; set; }
    public User(int userId, string firstname)
    {
        UserId = userId;
        Firstname = firstname;
    }
}
Ascending and Descending Sorting class list in linq C#:
List<User> UserList = new List<User>(); 

UserList.Add(new User(1, "bimal"));
UserList.Add(new User(2, "punit"));
UserList.Add(new User(3, "amit"));

UserList = UserList.OrderBy(x => x.Firstname).ToList();  //Ascending Sorted the class list using linq.
UserList = UserList.OrderByDescending(x => x.Firstname).ToList();  // Descending Sorted the class list using linq.


Related Other posts

Add,Update,delete DetailsView in asp.net c#

Add,Update,Delete,paging with DetailsView in asp.net c#
Introduction: In this article i will show you how to bind DetailsView in asp.net c# . I have implemented all operation like paging ,add ,edit and delete in DetailsView in asp.net c# . In following i have written the Css class to format the DetaildView.  
Html Code for DetailsView in asp.net :
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DetailView.aspx.cs" Inherits="HamidSite.DetailView" %>

<!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 id="Head1" runat="server">
    <title></title>
    <style type="text/css">
        .DetailsViewClass
        {
            font-family: verdana,arial,sans-serif;
            font-size: 11px;
            color: #333333;
            border-width: 1px;
            border-color: #999999;
            border-collapse: collapse;
            border-style: solid;
        }
        .Header
        {
            background: #b5cfd2;
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #999999;
        }
        .Foter
        {
            background: #dcddc0;
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #999999;
        }
        .btn
        {
            background: #ffffff;
            border-width: 1px;
            padding: 2px;
            border-style: solid;
            border-color: #999999;
            font-family: verdana,arial,sans-serif;
            font-size: 11px;
        }
        .textbox
        {
            border-width: 1px;
            padding: 1px;
            border-style: solid;
            border-color: #999999;
            font-family: verdana,arial,sans-serif;
            font-size: 11px;
            width: 100px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DetailsView ID="DetailsViewExample" AllowPaging="true" AutoGenerateRows="false"
            runat="server" Height="50px" CssClass="DetailsViewClass" CellPadding="4" OnPageIndexChanging="DetailsViewExample_PageIndexChanging"
            OnItemCommand="DetailsViewExample_ItemCommand1" OnItemUpdating="DetailsViewExample_ItemUpdating"
            OnModeChanging="DetailsViewExample_ModeChanging" OnItemInserting="DetailsViewExample_ItemInserting"
            Width="270px" OnItemDeleting="DetailsViewExample_ItemDeleting">
            <Fields>
                <asp:TemplateField HeaderText="First Name">
                    <ItemTemplate>
                        <asp:Label ID="lblID" Text='<%# Eval("ID") %>' Visible="false" runat="server"></asp:Label>
                        <asp:Label ID="lblFirstName" Text='<%# Eval("FirstName") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:Label ID="lblIDEdit" Text='<%# Eval("ID") %>' Visible="false" runat="server"></asp:Label>
                        <asp:TextBox ID="txtFirstname" Text='<%# Eval("FirstName") %>' runat="server" CssClass="textbox"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Last Name">
                    <ItemTemplate>
                        <asp:Label ID="lblLastName" Text='<%# Eval("LastName") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtLastName" Text='<%# Eval("LastName") %>' runat="server" CssClass="textbox"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="City">
                    <ItemTemplate>
                        <asp:Label ID="lbldob" Text='<%# Eval("City") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtCity" Text='<%# Eval("City") %>' runat="server" CssClass="textbox"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Address">
                    <ItemTemplate>
                        <asp:Label ID="lblAddress" Text='<%# Eval("Address") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtAddress" Text='<%# Eval("Address") %>' runat="server" CssClass="textbox"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Pin No">
                    <ItemTemplate>
                        <asp:Label ID="lblPinNo" Text='<%# Eval("PinNo") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtPinNo" Text='<%# Eval("PinNo") %>' runat="server" CssClass="textbox"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Mobile No">
                    <ItemTemplate>
                        <asp:Label ID="lblMobileNo" Text='<%# Eval("MobileNo") %>' runat="server"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtMobileNo" Text='<%# Eval("MobileNo") %>' runat="server" CssClass="textbox"></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:CommandField Visible="true" ShowInsertButton="true" ShowCancelButton="true"
                    ShowDeleteButton="true" ShowEditButton="true" />
            </Fields>
            <PagerStyle CssClass="Foter" />
            <FieldHeaderStyle Width="80px" CssClass="Header" />
        </asp:DetailsView>
    </div>
    </form>
</body>
</html>

C# Code for DetailsView in asp.net c# :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace HamidSite
{
    public partial class DetailView : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bindDetailtView();
            }
        }
        private void bindDetailtView()
        {
            try
            {
                DataSet Ds = GetDataSet("Select * from Employee");
                DetailsViewExample.DataSource = Ds;
                DetailsViewExample.DataBind();
            }
            catch (Exception ex) { throw ex; }
        }
        private DataSet GetDataSet(string Query)
        {
            DataSet Ds = new DataSet();
            try
            {
                string strCon = @"Data Source=ServerName;Initial Catalog=Test;Integrated Security=True";
                SqlConnection Con = new SqlConnection(strCon);
                SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
                Da.Fill(Ds);

            }
            catch (Exception) { }
            return Ds;
        }
        private void ExecuteQuery(string Query)
        {
            try
            {
                string strCon = @"Data Source=ServerName;Initial Catalog=Test;Integrated Security=True";
                SqlConnection Con = new SqlConnection(strCon);
                Con.Open();
                SqlCommand cmd = new SqlCommand(Query, Con);
                cmd.ExecuteNonQuery();
                Con.Close();
            }
            catch (Exception) { }
        }
        protected void DetailsViewExample_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
        {
            DetailsViewExample.PageIndex = e.NewPageIndex;
            bindDetailtView();
        }
        protected void DetailsViewExample_ItemCommand1(object sender, DetailsViewCommandEventArgs e)
        {
            switch (e.CommandName.ToString())
            {
                case "Edit":
                    DetailsViewExample.ChangeMode(DetailsViewMode.Edit);
                    bindDetailtView();
                    break;
                case "Cancel":
                    DetailsViewExample.ChangeMode(DetailsViewMode.ReadOnly);
                    bindDetailtView();
                    break;
                case "New":
                    DetailsViewExample.ChangeMode(DetailsViewMode.Insert);
                    bindDetailtView();
                    break;
            }
        }
        protected void DetailsViewExample_ModeChanging(object sender, DetailsViewModeEventArgs e)
        {
        }
        protected void DetailsViewExample_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
        {
            TextBox txtFirstname = (TextBox)DetailsViewExample.FindControl("txtFirstname");
            TextBox txtLastName = (TextBox)DetailsViewExample.FindControl("txtLastName");
            TextBox txtCity = (TextBox)DetailsViewExample.FindControl("txtCity");
            TextBox txtAddress = (TextBox)DetailsViewExample.FindControl("txtAddress");
            TextBox txtPinNo = (TextBox)DetailsViewExample.FindControl("txtPinNo");
            TextBox txtMobileNo = (TextBox)DetailsViewExample.FindControl("txtMobileNo");
            Label lblIDEdit = (Label)DetailsViewExample.FindControl("lblIDEdit");

            string Query = "Update Employee Set FirstName='" + txtFirstname.Text + "' ,LastName ='" + txtLastName.Text + "' ,City ='" + txtCity.Text + "',Address='" + txtAddress.Text + "',PinNo='" + txtPinNo.Text + "',MobileNo='" + txtMobileNo.Text + "' where ID =" + lblIDEdit.Text;
            ExecuteQuery(Query);
            DetailsViewExample.ChangeMode(DetailsViewMode.ReadOnly);
            bindDetailtView();
        }
        protected void DetailsViewExample_ItemInserting(object sender, DetailsViewInsertEventArgs e)
        {
            TextBox txtFirstname = (TextBox)DetailsViewExample.FindControl("txtFirstname");
            TextBox txtLastName = (TextBox)DetailsViewExample.FindControl("txtLastName");
            TextBox txtCity = (TextBox)DetailsViewExample.FindControl("txtCity");
            TextBox txtAddress = (TextBox)DetailsViewExample.FindControl("txtAddress");
            TextBox txtPinNo = (TextBox)DetailsViewExample.FindControl("txtPinNo");
            TextBox txtMobileNo = (TextBox)DetailsViewExample.FindControl("txtMobileNo");
            string Query = "Insert into Employee ([FirstName] ,[LastName] ,[City] ,[Address] ,[PinNo] ,[MobileNo]) values ('" + txtFirstname.Text + "' ,'" + txtLastName.Text + "' ,'" + txtCity.Text + "','" + txtAddress.Text + "','" + txtPinNo.Text + "','" + txtMobileNo.Text + "')";
            ExecuteQuery(Query);
            DetailsViewExample.ChangeMode(DetailsViewMode.ReadOnly);
            bindDetailtView();
        }
        protected void DetailsViewExample_ItemDeleting(object sender, DetailsViewDeleteEventArgs e)
        {
            Label lblID = (Label)DetailsViewExample.FindControl("lblID");
            string Query = "Delete from Employee where ID =" + lblID.Text;
            ExecuteQuery(Query);
            bindDetailtView();
        }
    }
}

Related Other posts

Sunday, January 29, 2012

Export gridview to excel in Asp.net

Export gridview to excel in Asp.net :

Introduction : In this article i will show you how to export GridView to excel file. Many times we require to export the GridView to excel sheet file.I have here written following code in asp.net c# to export the gridview control to excel sheet file.

Html code for gridview export to excel sheet :
<asp:GridView ID="GridViewExample" runat="server" AutoGenerateColumns="False" BackColor="White"
    BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4">
    <Columns>
        <asp:TemplateField HeaderText="City Name" SortExpression="Name" FooterStyle-Width="200px"
            ItemStyle-Width="200px">
            <ItemTemplate>
                <asp:Label ID="lblCityName" Text='<%#Bind("Name")%>' runat="server"></asp:Label>
            </ItemTemplate>
            <FooterStyle Width="200px"></FooterStyle>
            <ItemStyle Width="200px"></ItemStyle>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="STD Code" SortExpression="STDCode" FooterStyle-Width="100px"
            ItemStyle-Width="100px">
            <ItemTemplate>
                <asp:Label ID="lblSTDCOde" Text='<%#Bind("STDCode")%>' runat="server"></asp:Label>
            </ItemTemplate>
            <FooterStyle Width="100px"></FooterStyle>
            <ItemStyle Width="100px"></ItemStyle>
        </asp:TemplateField>
    </Columns>
    <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
    <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
    <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
    <RowStyle BackColor="White" ForeColor="#003399" />
    <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
    <SortedAscendingCellStyle BackColor="#EDF6F6" />
    <SortedAscendingHeaderStyle BackColor="#0D4AC4" />
    <SortedDescendingCellStyle BackColor="#D6DFDF" />
    <SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
<asp:Button ID="btnExport" BackColor="#003399" Text="Export To Excel" runat="server"
    OnClick="btnExport_Click" />
C# Code to export the gridview to excel sheet :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;

namespace HamidSite
{
    public partial class GridviewExportToExcel : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGridView();
            }
        }

        private void BindGridView()
        {
            try
            {
                DataTable Dt = GetDataTable("Select Name ,stdcode from citytable");
                GridViewExample.DataSource = Dt;
                GridViewExample.DataBind();

            }
            catch (Exception)
            {
                throw;
            }
        }
        private DataTable GetDataTable(string Query)
        {
            DataSet Ds = new DataSet();
            try
            {
                string strCon = @"Data Source=ServerName;Initial Catalog=Test;Integrated Security=True;";  //Conntection String
                SqlConnection Con = new SqlConnection(strCon);
                SqlDataAdapter Da = new SqlDataAdapter(Query, Con);
                Da.Fill(Ds);
            }
            catch (Exception) { }
            return Ds.Tables[0];
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExample.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.xls";

            StringWriter StringWriter = new System.IO.StringWriter();
            HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);

            GridViewExample.RenderControl(HtmlTextWriter);
            Response.Write(StringWriter.ToString());
            Response.End();
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
        }
    }
}

Related Other posts

Saturday, January 28, 2012

Css Class for textbox in asp.net

Css Class for textbox in asp.net

Introduction : In this i will show you Css Class for textbox in asp.net . You just need apply cssClass that on textbox .

Css Class for TextBox :

<style type="text/css">
    .txtclass
    {
        font-family: Tahoma,Arial, Helvetica, sans-serif;
        font-size: 11px;
        color: #000000;
        font-weight: normal;
        text-decoration: none;
        border: 1px solid #888888;
    }
</style>

Apply Css Class to textbox as follow : 

<asp:TextBox ID="txtname" CssClass="txtclass" runat="server"></asp:TextBox>

Related Other posts