Sunday, July 26, 2009

Static Class and Static Method and Static Member

I am assuming that you know static class and static members refer http://msdn.microsoft.com/en-us/library/79b3xss3.aspx to know about it.

Let’ examine the static class and static members in detail using below points

1. Static Class and NonStatic Class are same?


Lets Create static class like below:

  public static class StaticClass
    {
        public static void MyFirstMethod()
        {
            //Code Goes Here
        }
        public static void MySecondMethod()
        {
            //Code Goes Here
        }
    }


MyFirstMethod and MySecondMethod can be called using class name like below.

StaticClass.MyFirstMethod();        
StaticClass.MySecondMethod();


And non static class like below:

public class NonStaticClass
    {
        public static void MyFirstMethod()
        {
            //Code Goes Here
        }


        public static void MySecondMethod()
        {
            //Code Goes Here
        }
    }



MyFirstMethod and MySecondMethod can be called using class name like below.

NonStaticClass.MyFirstMethod();  
NonStaticClass.MySecondMethod();



StaticClass and NonStaticClass have same behavior so far. If the behavior is same why do we need static class, let’s examine it more.

2. Static Class and NonStatic Class are not same because Static class is sealed?



As we know static class is sealed, we can’t inherit static class, let’ create a class MyClass and try to inherit static class like below:

 class MyClass : StaticClass
    {    

    }



You will get compile time error “'StaticClassTest.MyClass': cannot derive from static class 'StaticClassTest.StaticClass'

Now make the NonStaticClass which we have just created as sealed like below:

   public sealed class NonStaticClass
    {
        public static void MyFirstMethod()
        {
            //Code Goes Here
        }

        public static void MySecondMethod()
        {
            //Code Goes Here
        }
    }



Now inherit NonStaticClass to MyClass


class MyClass : NonStaticClass
    {       


    }



You will get compile time error “'StaticClassTest.MyClass': cannot derive from sealed type 'StaticClassTest.NonStaticClass'”

Still StaticClass and NonStaticClass are same, So far all the features provided by StaticClass can be achieved using NonStaticClass. If the behaviour same what is the difference, let’s examine it more

3. Static Class and NonStatic Class are not same because Static class cannot contain instance constructors?

Let’s modify the StaticClassTest and make it like below which is having constructor

public static class StaticClass
    {
        static StaticClass(string MyName)
        {
        }

        public static void MyFirstMethod()
        {
            //Code Goes Here
        }

        public static void MySecondMethod()
        {
            //Code Goes Here
        }
    }



You will get compile time error “'StaticClassTest.StaticClass.StaticClass(string)': a static constructor must be parameterless”

Let’s modify the NonStaticClass and make it like below which is having constructor


public sealed class NonStaticClass
    {
        public NonStaticClass(string MyName)
        {
            //Code Goes Here
        }


        public static void MyFirstMethod()
        {
            //Code Goes Here
        }


        public static void MySecondMethod()
        {
            //Code Goes Here
        }
    }



Compile the application, it will compile without any error.

Call MyFirstMethod of NonStaticClass like below

NonStaticClass.MyFirstMethod();



Put a break point on the constructor of NonStaticClass. You will notice constructor won’t be called only MyFirstMethod will called.

Now create object of NonStaticClass like below

NonStaticClass objNonStaticClass = new NonStaticClass("test");


Constructor of NonStaticClass will be called at this time.

Conclusion:

Normal class with all static members is equivalent to static members of static Class, if you don't intend to inherit normal class.
Normal sealed class with all the static members is equivalent to static members of static Class.
Normal sealed class with all static members and a paramerized constructor is not equivalent to static members of static Class because static class doesn’t permit paramerized constructor.

Decision to use static class
Static classes should be used when a class doesn't have any behaviour as such. Like utility or helper class, the methods in utility and helper class need to be called several times, there is no need to create instance of the class on each call. This will improve the performance as object creation is not involved on each call.

Why static class will improve performance?

There is division of memory within a process

1. Stack
2. Heap
3. Static, which is High Frequency Heap.

The member data of static class is stored in High Frequency Heap which is handled differently than regular object heap. This area of heap is not garbage collected. It means GC doesn't have overhead like regular class which need to be garbage collected when it is unreachable. Static class doesn't get constructed until it is used.

Wednesday, July 8, 2009

Create Dynamic DropDownList

1. Create a DynamicDropDownlist.aspx and place a placeholder and two buttons with name btnCreate and btnRetrieve. 



<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<
asp:Button ID="btnCreate" runat="server" Text="Create DropDownList" />
<
asp:Button ID="Retrieve" runat="server" Text="Button" onclick="btnRetrieve_Click" />


2. Create a class level Control variable and assign null to it.


Control cause = null;

3. Create CreateDropDownListControl method. This method will create dropdownlist, copy and paste below code.



public static Control GetPostBackControl(Page page)
{
      Control control = null;
      
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
      
if (ctrlname != null && ctrlname != string.Empty)
      {
            control = page.FindControl(ctrlname);
      }
      
else
      
{
            
foreach (string ctl in page.Request.Form)
            {
                  Control c = page.FindControl(ctl);
                  
if (c is System.Web.UI.WebControls.Button)
                  {
                        control = c;
                        
break;
                  }
            }
      }
      return control;
}


4. Create Page_Init method, copy and paste below code.


protected void Page_Init(object sender, EventArgs e)
{
      if (IsPostBack)
      {
            //Method to get the control which caused postback
            
cause = GetPostBackControl(Page);
            
//To make sure new dropdownlist get create on click of
create DropDownList
            
if (cause != null && cause.ID.Equals("btnCreate"))
            {
                  CreateDropDownListControl();
            }
            
//To re-create control in case of any postback excluding click of Create DropDownList
            
else if (cause == null || !cause.ID.Equals("btnCreate"))
            {
                  CreateDropDownListControl();
            }
      }
}

5. OnSelectedIndexChanged method will return value of the selected dropdownlist index,Copy and paste below code. 



protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
      DropDownList ddl = (DropDownList)sender;
      Response.Write(ddl.SelectedItem.Text);
}


6. btnRetrieve_Click method will return value of the all selected dropdownlist index,Copy and paste below code.



protected void btnRetrieve_Click(object sender, EventArgs e)
{
      int ddlCount = Convert.ToInt32(Session["Count"].ToString());
      for (int i = 0; i < ddlCount; i++)
      {
            Response.Write(
"Selected Dropdownlist values are " + Request.Form["ddl" + i.ToString()] + "</br>");
      }
}


Lets' put all together in DynamicDropDownlist.aspx.cs file.



using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;






public partial class DynamicDropDownlist : System.Web.UI.Page
{
      Connrol cause = null;
      
protected void Page_Init(object sender, EventArgs e)
      {
            
if (IsPostBack)
            {
                  
//Method to get the control which caused postback
                  cause = GetPostBackControl(Page);
                  
//To make sure new dropdownlist get create on click of Create DropDownList
                  
if (cause != null && cause.ID.Equals("btnCreate"))
                  {
                        CreateDropDownListControl();
                  }
                  
//To re-create control in case of any postback excluding click of Create DropDownList
                  
else if (cause == null || !cause.ID.Equals("btnCreate"))
                  {
                        CreateDropDownListControl();
                  }
            }
      }
      public static Control GetPostBackControl(Page page)
      {
            
Control control = null;
            
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
            
if (ctrlname != null && ctrlname != string.Empty)
            {
                  control = page.FindControl(ctrlname);
            }
            
else
            
{
                  
foreach (string ctl in page.Request.Form)
                  {
                        
Control c = page.FindControl(ctl);
                        
if (c is System.Web.UI.WebControls.Button)
                        {
                              control = c;
                              
break;
                        }
                  }
             }
             
return control;
      }

      protected void Page_Load(object sender, EventArgs e)
      {
      }




      protected void btnRetrieve_Click(object sender, EventArgs e)
      {
            
int ddlCount = Convert.ToInt32(Session["Count"].ToString());
            for (int i = 0; i < ddlCount; i++)
            {
                  Response.Write(
"Selected Dropdownlist values are " + Request.Form["ddl" + i.ToString()] + "</br>");
            }
      }


      protected void CreateDropDownListControl()
      {
            
if (Session["Count"] == null)
            {
                  
DropDownList ddl = new DropDownList();
                  ddl.ID =
"ddl0";
                  ddl.AutoPostBack =
true;
                  ddl.Items.Add(
new ListItem("Test0", "0"));
                  ddl.Items.Add(
new ListItem("Test1", "1"));
                  ddl.SelectedIndexChanged +=
new EventHandler
OnSelectedIndexChanged);
                  PlaceHolder1.Controls.Add(ddl);
                  Session[
"Count"] = "1";
            }
            
else
            
{
                  
int ctrlCount = 0;
                  
if (cause != null && cause.ID.Equals("btnCreate"))
                  {
                        
ctrlCount =
Convert.ToInt32(Session["Count"].ToString()) + 1;
                        Session[
"Count"] = (Convert.ToInt32(Session["Count"].ToString()) + 1).ToString();
                  }
                  
else
                  
{
                        ctrlCount =
Convert.ToInt32(Session["Count"].ToString());
                  }
                  
for (int i = 0; i < ctrlCount; i++)
                  {
                        
DropDownList ddl = new DropDownList();
                        ddl.ID =
"ddl" + i.ToString();
                        ddl.AutoPostBack =
true;
                        ddl.Items.Add(
new ListItem("Test" + i.ToString(), "0"));
                        ddl.Items.Add(
new ListItem("Test" + (i + 1).ToString(), "1"));
                        ddl.SelectedIndexChanged +=
new EventHandler(OnSelectedIndexChanged);
                        PlaceHolder1.Controls.Add(ddl);
                  }
            }
      }




      protected void OnSelectedIndexChanged(object sender, EventArgs e)
      {
            DropDownList ddl = (DropDownList)sender;
            Response.Write(ddl.SelectedItem.Text);
      }


}


Happy Coding :)

Friday, June 5, 2009

Paging in GridView

This artilce explains how to paging in GridView. I have created a database called Test in SQL which contains a Emplyee table having Name,Country,City and Age as column.

1. Place a GridView control on the aspx page with pagesize as 10 and OnPageIndexChanging="MyGrid_PageIndexChanging" which will call code behind method for paging. PageSize denotes number of rows to be appeared on at a time


<asp:GridView ID="MyGrid" runat="server" AllowPaging="True" PageSize="10" OnPageIndexChanging="MyGrid_PageIndexChanging"></asp:GridView>



2. Import below namespace to get data from the database using SQL objects


using System.Data;
using System.Data.SqlClient;


3. Create SQL connection and command object to retrieve data from database.


SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("GetEmployee", conn);
cmd.CommandType =
CommandType.StoredProcedure;



4. Create SQLDataAdapter object and populate datatable with data


SqlDataAdapter mySqlAdapter = new SqlDataAdapter(cmd);
DataTable myDataTable = new DataTable();
mySqlAdapter.Fill(myDataTable);



5. Create Stored Procedure to get data from database.


CREATE  PROCEDURE GetEmployee
AS
BEGIN
 Select Name,Country,City,Age  FROM EMPLOYEE
END



6. Bind GridView to DataTable

MyGrid.DataSource = myDataTable;
MyGrid.DataBind();


7. Create Page indexing method for paging


protected void MyGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{ 
   MyGrid.PageIndex = e.NewPageIndex;
   BindGridView();
}



8. Page_Load will contain call to BindGridView() method to bind the data to GridView first time when page loads.

protected void Page_Load(object sender, EventArgs e)
{
     if(!IsPostBack)
        BindGridView();
}


9. Let's put all together

i) Put gridview control on aspx page


<asp:GridView ID="MyGrid" runat="server" AllowPaging="True" PageSize="10" OnPageIndexChanging="MyGrid_PageIndexChanging"></asp:GridView>



ii) Code Behind code


protected void Page_Load(object sender, EventArgs e)
{
     if(!IsPostBack)
          BindGridView();
}


protected void MyGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{ 
     MyGrid.PageIndex = e.NewPageIndex; 
     BindGridView();
}


public void BindGridView()
{
     string connectionString = "Data Source=localhost;Initial      Catalog=Test;Integrated Security=True";
     SqlConnection conn = null;
     string strName = string.Empty;
     try
     {
          conn =
new SqlConnection(connectionString);
          conn.Open();
         
SqlCommand cmd = new SqlCommand("GetEmployee", conn);
          cmd.CommandType =
CommandType.StoredProcedure;
         
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(cmd);
         
DataTable myDataTable = new DataTable();
          mySqlAdapter.Fill(myDataTable);
          MyGrid.DataSource = myDataTable;
          MyGrid.DataBind();
     }
     catch (Exception ex)
     {
          Response.Write(ex.Message);
     }
     finally
     {
          //Closing connection in finally block in case of any exception, conn should close.
         
// close connection
         
if (conn != null)
          {
               conn.Close();
          }
     }
}

Thursday, June 4, 2009

ADO.NET Select Stored Procedure using SQLParameter

This artilce explains how to use parameters in the command. I have created a database called Test in SQL which contains a UserDetail table having UserId and Password as column.

1.Import below namespace


using System.Data;
using System.Data.SqlClient;

2. Create and open SQLConnection



string connectionString = "Data Source=localhost;Initial Catalog=Test;Integrated Security=True";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();


3. Create stored procedure



CREATE PROCEDURE GetUserDetail
@UserId VARCHAR(50),
@Password VARCHAR(50)
AS
BEGIN
 Select UserId From UserDetail WHERE UserId = @UserId AND Password = @Password
END



4. Create SQLCommand Objects




SqlCommand cmd = new SqlCommand("GetUserDetail", conn);
cmd.CommandType =
CommandType.StoredProcedure;


5. Create SqlParameter Objects and bind it to SQLCommand objects

SqlParameter
[] param = new SqlParameter[2];
param[0] =
new SqlParameter("@UserId", strUserId);
param[1] =
new SqlParameter("@Password", strPassword);
//add parameters to command object
cmd.Parameters.Add(param[0]);
cmd.Parameters.Add(param[1]);


6. Get Data from DB

//get data stream
SqlDataReader reader = cmd.ExecuteReader();
//Check whether record exists or not
if (reader.HasRows)
{
     // Loop through each record
    
while (reader.Read())
     {
          strName = reader[
"UserId"].ToString();
     }
}
else
{
     Response.Write("Record not found.");
}

 


Let's Put all together

string connectionString = "Data Source=localhost;Initial Catalog=Test;Integrated Security=True";
SqlConnection conn =
null;
SqlDataReader reader =
null;
string strUserId = "myName";
string strPassword = "myPassword";
string strName = string.Empty;
try
{
     conn =
new SqlConnection(connectionString);
     conn.Open();
    
SqlCommand cmd = new SqlCommand("GetUserDetail", conn);
     cmd.CommandType =
CommandType.StoredProcedure;

     
SqlParameter[] param = new SqlParameter[2];
     param[0] =
new SqlParameter("@UserId", strUserId);
     param[1] =
new SqlParameter("@Password", strPassword);
     
//add new parameter to command object
     
cmd.Parameters.Add(param[0]);
     cmd.Parameters.Add(param[1]);
     
//get data stream
     reader = cmd.ExecuteReader();
     //Check whether record exists or not
     
if (reader.HasRows)
     {
          
// Loop through each record
          
while (reader.Read())
          {
               strName = reader[
"UserId"].ToString();
          }
     }
     
else
     {
          Response.Write(
"Record not found.");
     }
}
catch (Exception ex)
{
}
finally
{
     //Closing reader and connection in finally block in case  of any exception reader and conn should close.
     //Code in finally block executes in normal scenario as well as in case of exception thrown.
     if (reader != null)
     {
          reader.Close();
     }
     // close connection
     
if (conn != null)
     {
          conn.Close();
     }
}




 


Happy Coding :)

Site Meter