Monday 4 April 2011

How to use #region in C# code?

How to use #region in C# code?
Region is used to group of your specified code. We can use region block in any number of times in our server side code.
Advantages:
Easily understood code block by new user when refer your project first time.
Copy to particular block is easy when you use region in that block.
How to code for region block?
You can put your code in side of block region syntax block
#region set any region name
//Your code
#endregion
Example for without using Region Block in C# code
using System.Data;
using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
    SqlConnection sqlcon = new SqlConnection(@"Server=RAVI\SQLEXPRESS;database=test;uid=xxxx;pwd=yyyy;");
    SqlCommand sqlcmd = new SqlCommand();
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable dt = new DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {
        BindGrid();
    }
   void BindGrid()
    {
        try
        {
            sqlcon.Open();
            sqlcmd = new SqlCommand("select * from emp", sqlcon);
            da = new SqlDataAdapter(sqlcmd);
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }

        catch (Exception e)
        {
            Response.Write(e.ToString());
        }
        finally {
            sqlcon.Close();
        }

    }
}

Example for with use of Region Block in C# code
using System.Data;
using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
   #region Declaration part
    SqlConnection sqlcon = new SqlConnection(@"Server=System3\SQLEXPRESS;database=test;uid=ravindran;pwd=srirangam;");
    SqlCommand sqlcmd = new SqlCommand();
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable dt = new DataTable();
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        BindGrid();
    }
 
#region Bind data from SQL table to GridView
    void BindGrid()
    {
        try
        {
            sqlcon.Open();
            sqlcmd = new SqlCommand("select * from emp", sqlcon);
            da = new SqlDataAdapter(sqlcmd);
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }

        catch (Exception e)
        {
            Response.Write(e.ToString());
        }
        finally {
            sqlcon.Close();
        }

    }
   #endregion
}

After add region in your code then show simplify your code use of region blocks

No comments:

Post a Comment