Friday, January 30, 2015

A Simple Use of SQL CASE Expression

We normally use ‘SELECT’ query during database operations to fetch the data from database in SQL, like

select * from tbl_order_Master

Output



Let’s suppose we need to show Customer Name Virat to Virat Kohli during fetching the data via SELECT query in SQL SERVER.

In this circumastances we need to apply CASE in sql query like that

select (case when customerName='Virat' then 'Virat Kohli' else Customername end) as CustomerName ,Item ,Bill from tbl_order_Master

Output



How we can apply more than one cases in one SELECT Query –

Let’s suppose we need to show Customer Name Virat to Virat Kohli and Dhoni to MS Dhoni  during fetching the data via one SELECT query in SQL SERVER.

In this circumastances we need to apply Two CASES in sql query like that

select (case when customerName='Virat' then 'Virat Kohli' else case When customername='Dhoni' then 'MS Dhoni' else  Customername end end) as CustomerName ,Item ,Bill from tbl_order_Master

Output



USE- Now the question is when we use these cases or in Which circumastances we need to apply this.

Answer- Normally we use these cases when we don’t want to change the entry in database permanently and want to display different entry instead of actual entry for some places .

For Example- We want to create a report in which we need to show the Customers name who have placed the report, and there is a Customer Name Kohli  and we want to show that Virat Kohli without changing the name entry permanently then we use CASE in SELECT query

                                              Author- Er. Rahul Kr. Yadav

Out keyword in C#

As you know, a return statement enables a method to return a value to its caller. However, a method can return only one value each time it is called. What if you need to return two or more piece of information?

For example: What if you want to create a method that decomposes a floating-point number into its integer and fractional parts? To do this requires that two pieces of information be returned: the integer portion and the fractional component, this method cannot be written using only a single return value. The Out modifier solves this problem.

Use out

An out parameter is similar to a ref parameter with this one exception. It can only be used to pass a value out of a method.
It is not necessary to give the variable used as an out parameter an initial value prior to calling the method. The method will give the variable a value. Furthermore, inside the method, an out parameter is considered unassigned; that is, it is assumed to have no initial value. This implies that the method must assign the parameter a value prior to the method termination. Thus, after the call to the method, an out parameter will contain a value.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace use_out
{
    class decomp
    {
        public int Twoval(double n, out double frac)
        {
            int whole;
            whole = (int)n;
            frac = n - whole;
            return whole;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            decomp obj = new decomp();
            int a;
            double f;
            a =obj.Twoval (20.125,out f);
            Console.WriteLine("integer part is" + a);
            Console.WriteLine("fractional part is" + f);
            Console.Read();
        }
    }
}

Output



Note: Twoval() method return two piece of information. First is integer portion of n is returned as Twoval()’s return value. Second, the fractional portion of n is passed back to the caller through the out parameter frac. So the above mention example it is possible for one method to return two values.  

                                                        Author-Sayta Prakash

Monday, January 26, 2015

Ref Keyword in C#

By default when you pass argument to a method is value type. This means that change to the parameter that receives a value type will not affect the actual argument used in the call. But Through the use the ref, it is possible to pass any type of value as reference.

Before going into the mechanics of using ref, it is useful to understand why you might to pass a value type by reference reason is that

1.    It allows a method to alter the contents of its arguments.

Some time you will want a method to be able to operate on the actual arguments that are passed to it. Example: Swap() method that exchange the values of its two argument

Use of ref

The ref parameter modifier causes C# to create a call-by-reference, rather than a call-by-value. The ref modifier is specified when the method is declared and when it is called.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace use_ref
{
    class refdemo
    {
        public void sqr(ref int i)
        {
            i = i * i;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            refdemo obj = new refdemo();
            int a = 5;
            Console.WriteLine("a before call:" + a);
            obj.sqr(ref a);
            Console.WriteLine("a after call:" + a);
            Console.Read();
        }
    }
}


Note: Ref precedes the entire parameter declaration in the method and that is precedes the argument when the method is called.
Output of program



So using ref, it is now possible to write a method that exchanges the value of it two values of its two value-type arguments.

Example 2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace swap
{
    class valswap
    {
        public void swap(ref int a, ref int b)
        {
            int temp;
            temp = a;
            a = b;
            b = temp;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            valswap obj = new valswap();
            int x = 5;
            int y = 10;
            Console.WriteLine("x and y before call:" + x +" " + y);
            obj.swap(ref x, ref y);
            Console.WriteLine("x and y after call:" + x +" " + y);
          
        }
    }
}

Output of program


                                                              Author-Sayta Prakash

Thursday, January 22, 2015

Params in C#

When you create a method, you usually know in advance the number of arguments that you will be passing to it, but this is not always the case. Sometime you will want to create a method that can be passed an arbitrary number of arguments.

For example: I want to create a method that find smallest from the set of values. Such type of method cannot create cannot be created using a normal parameters. Instead, you must use a special type of parameter that stands for an arbitrary number of parameters.
This is done by creating a params parameter.

Params modifier is used to declare an array parameter that will be able to receive zero or more arguments. The number of elements in the array will be equal to the number of arguments passed to the method. You program then accesses the array to obtain the arguments.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace use_params
{
    class smallest
    {
        public int smallval(params int[] nums)
        {
           
            if (nums.Length == 0)
            {
                Console.WriteLine("error no argument ");
                return 0;
            }
          int n = nums[0];
            for (int i = 1; i < nums.Length; i++)
            {
                if (nums[i] < n)
                {
                    n = nums[i];
                  
                }
            }
            return n;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            smallest obj = new smallest();
            int small;
            int a = 5, b = 10;
            small = obj.smallval(a, b);
            Console.WriteLine("smallest value is " + small);
            small = obj.smallval(a, b, 2);
            Console.WriteLine("smallest value of three argument is " + small);
            small = obj.smallval(a, b, 18, 24, 45, 1);
            Console.WriteLine("smallest value of six argument is " + small);
            int[] arg = { 12, 25, 36, 96, 56, 21 };
            small = obj.smallval(arg);
            Console.WriteLine("minimum value of args " + small);
           Console.Read();
        }
    }
}
 
Output


Note: Here above mention example smallval() is called, the arguments are passed to passed via the nums array. Length of the array equal to the array of elements.

                                                        Author-Satya Prakash

Notice: The last call to smallval(). Rather than being the values individually, it is passed an array containing the values. This is a perfectly legal. When a params parameter is created, it will accept either a variable-length list of argument or an array containing the arguments.

Monday, January 19, 2015

Gridview Custom Paging in ASP. Net Using Stored Procedure

In This article I am going to explain about how to Create Custom Paging in Grid\view Control. But Before going in depth let us first all understand the need of custom paging.
Suppose your database contain more than thousand record and you need to display only Ten record per page. In This situation Custom paging is more useful be because you may not want to show 1000-10=990 extra record which reduce the performance and improve the complicity. 

 So create the custom paging first of all create Stored procedure because I will create custom paging through help of Stored Procedure.

 Create PROCEDURE custompaging
 (
       @PageIndex INT,
       @PageSize INT,
       @totalrecord INT OUTPUT
 )
     
AS
BEGIN
      SET NOCOUNT ON
      SELECT ROW_NUMBER() OVER( ORDER BY id ASC)AS RowNumber,id,name, salary INTO #Results FROM emp    
      SELECT @totalrecord = COUNT(*) FROM #Results          
      SELECT * FROM #Results
      WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1    
      DROP TABLE #Results
END
 
Note: IN above declared procedure I have Used ROW_NUMBER() keyword which give us row numbers of records that you can select from the table.
Now Open a Empty web site and take a Gridview control for display the record of table and one Repeater control at the bottom of Gridview for create the paging.

Default.aspx code

<%@ 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></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID ="Gridview1" runat ="server" AutoGenerateColumns ="false" >
    <Columns>
    <asp:BoundField HeaderText ="Id" DataField ="rownumber" />
    <asp:BoundField HeaderText ="Name" DataField ="name" />
    <asp:BoundField HeaderText ="Salary" DataField ="salary" />
    </Columns>
    </asp:GridView>
    <asp:Repeater ID ="repeater1" runat ="server" >
    <ItemTemplate >
    <asp:LinkButton ID ="linkbutton1" runat ="server" Text ='<%#Eval("Text") %>' CommandArgument ='<%#Eval("Value") %>' Enabled ='<%#Eval("Enabled") %>' OnClick ="Page_size"></asp:LinkButton>
    </ItemTemplate>
    </asp:Repeater>
    </form>
</body>
</html>
 
Default.aspx.cs Code
 
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;
using System.Configuration;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.ShowdetailPageWise(1);
    }
 
    private void ShowdetailPageWise(int pageIndex)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString);
        SqlCommand cmd = new SqlCommand("custompaging", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@pageindex", pageIndex);
        cmd.Parameters.AddWithValue("@pagesize", 3);
        cmd .Parameters .Add ("@totalrecord",SqlDbType.Int,3);
        cmd.Parameters["@totalrecord"].Direction = ParameterDirection.Output;
        con.Open();
        IDataReader dr = cmd.ExecuteReader();
        Gridview1.DataSource = dr;
        Gridview1.DataBind();
        dr.Close();
        con.Close();
        int totalrecord = Convert.ToInt32(cmd.Parameters["@totalrecord"].Value);
        this.pagination(totalrecord, pageIndex);
     }
    public void pagination(int totalrecord, int pageindex)
    {  
        double totalpage = (double)((decimal)totalrecord  /3 );
        int pageCount = (int)Math.Ceiling(totalpage);
        List<ListItem> pages = new List<ListItem>();
        if (pageCount > 0)
        {                          
            pages.Add(new ListItem("First", "1", pageindex > 1));
                   
            for (int i = 1; i <= pageCount; i++)
            {
                pages.Add(new ListItem(i.ToString(), i.ToString(), i != pageindex));
            }         
            pages.Add(new ListItem("Last", pageCount.ToString(), pageindex  < pageCount));
        }
        repeater1.DataSource = pages;
        repeater1.DataBind();
}
    protected void Page_size(object sender, EventArgs e)
    {
       int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
       this.ShowdetailPageWise(pageIndex);
    }
}
 
Note: Above declared code I have used Two Method One for Show the table record in Gridview control and other method is Pagination which is used to create the custom paging at the bottom of Gridview.
 
I have created connection string in Web.config file.
 
  <connectionStrings>
    <add name="Myconnection" connectionString="Data Source=MCNDESKTOP08;Initial Catalog=pulkit;User ID=sa;Password=*********"/>
  </connectionStrings>
 
OutPut