How to add script reference in Master Page to make accessible from all the directory


To add script file reference in master page to make it accessible from all the pages from all the directory of the website , add the script reference in the following way :

Suppose the web structure is as follows :

Structure of the WebSite

add following lines to masterpage.master

<head runat=”server”>
    <title></title>
    <script type=”text/javascript” src='<%#ResolveUrl(“~/JQuery/jquery-ui-1.8.17.custom/js/jquery-1.7.1.min.js” ) %>’ ></script>
    <script type=”text/javascript” src='<%#ResolveUrl(“~/JQuery/jquery-ui-1.8.17.custom/js/jquery-ui-1.8.17.custom.min.js” ) %>’ ></script>
</head>

And then add Page.Header.DataBind();  in the OnLoad method of the MasterPage.master.cs file :

protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        Page.Header.DataBind();
    }

 

Thats it, now functionality from the script files are available to all the files in the website that uses the master page.

 

Advertisements

How to call webservice method by asp.net ajax.


Its very easy to call webservice method from client side using asp.net ajax. Following steps are the minimal things needed to

call webservice method from asp.net page using asp.net ajax :

1. Create a asp.net website using Visual studio(Here I am using Visual studio 2010), Lets name it WSCallFeatureTest.

2. Now add a new webform lets name it CallWebservice.aspx.

3. Add a new webservice file(.asmx) name it WebService.asmx

4. Add a webservice method to the WebService.asmx file. Below is the sample method by which I will test.

The content of the webservice class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = “http://tempuri.org/&#8221;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

public WebService () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string HelloWorld() {
return “Hello World”;
}

}

5. Now its time to call the webservice method HelloWorld from the webform. To call the webservice method from the webform
have to add the ScriptManager to the page and have to add the webservice referrence to the page. The following content serve

this things.
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePartialRendering=”true”>
<Services>
<asp:ServiceReference Path=”~/WebService.asmx” />
</Services>
</asp:ScriptManager>

and a button will be added to the page this button will call the webservice method. The total content of the web form is

given below :

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”CallWebservice.aspx.cs” Inherits=”CallWebservice” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>
<script type=”text/javascript” language=”javascript”>

function GetWSValue() {

WebService.HelloWorld(WsCompleted);

return false;
}

function WsCompleted(result) {

if (result != null) {
alert(result);
}
}

</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<asp:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePartialRendering=”true”>
<Services>
<asp:ServiceReference Path=”~/WebService.asmx” />
</Services>
</asp:ScriptManager>
<table>
<tr>
<td>
&nbsp;
</td>
<td>
<asp:Button ID=”btnGetValue” runat=”server” Text=”GetWSValue” OnClientClick=”return GetWSValue();”  />
</td>
</tr>
</table>
</form>
</body>
</html>

6. Clicking on the button will call webservice method HelloWold and will show the result on the alert.

How to show watermark text for password field


The code below shows how to show water mark text for password field.

  <html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head id=”Head1″ runat=”server”>
    <title></title>
    <script type=”text/javascript” src=”JQuery/jquery-1.4.1-vsdoc.js”></script>
    <script type=”text/javascript”>

        $(document).ready(function () {

            $(“#txtPasswordWaterMark”).show();
            $(“#txtPasswordWaterMark”).addClass(“waterMark”);
            $(“#txtPasswordWaterMark”).val(“Password”);
            $(“#<%= txtPassword.ClientID  %>”).hide();

            $(“#txtPasswordWaterMark”).focus(function () {
                $(this).hide();
                $(“#<%= txtPassword.ClientID  %>”).show();
                $(“#<%= txtPassword.ClientID  %>”).focus();
            });

//            $(“#txtPasswordWaterMark”).keydown(function () {
//                $(this).hide();
//                $(“#<%= txtPassword.ClientID  %>”).show();
//                $(“#<%= txtPassword.ClientID  %>”).focus();
//            });

            $(“#<%= txtPassword.ClientID  %>”).blur(function () {

                if ($(this).val() == “”) {
                    $(“#<%= txtPassword.ClientID  %>”).hide();
                    $(“#txtPasswordWaterMark”).show();
                }

            });

        });

    </script>
    <style type=”text/css”>

      .waterMark{
            color : #9B9B9B;
        }

    </style>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
     <asp:TextBox ID=”txtPassword” TextMode=”Password” runat=”server”></asp:TextBox>
     <input type=”text” id=”txtPasswordWaterMark” />
    </div>
    </form>
</body>
</html>

 

Note : Jquery needed to run the above code.

How to show validation summary on change event or any other event when it required.


What leads me to develop the validation summary control?

Last week it was very much pain for me to manage the validation summary of application input forms. Normally in ASP.Net the validation summary fires on form submit. but our client requirement was to fire the validation summary on any input change by user.

To meet the client requirement I look for jquery validation plugins and some other but the plugins that I found doesn’t meet my client requirement. Then I decide to make a validation summary control from scratch but It seemed to me that it will be very tricky to implement it from scratch and to support for all the browsers. So I came up with a solution to build a validation control by mixing with ASP.Net existing validation controls and Jquery. So the validation of data will be done by validation control and I will just manage it to show whenever it requires. So my work now reduces to only doing show hides of the validations.

Introduction :  The control works for showing validation summary whenever it requires. It’s build by mixing up ASP.Net validation control and Jquery. I will point some of the flexibilities and features of the control below:

Ø      As its build with ASP.Net validation control, so the validation is done by ASP.Net validation control, as a result it will be painless to validate the data and  will be compatible with the browsers to which ASP.Net validation controls are compatible with.

Ø      It’s very much flexible to validate data whenever needed. The summary can be updated on any event it required. Obviously on form submit, onchange and any other event.

Ø      The style of the validation summary can be controlled by changing the CSS.

Prerequisites and Limitation: The limitation is it’s only useable in asp.net application. And a prerequisite is it requires jquery.

The code to use the validation control:

Download the required files from here validation summary.

And also download the jquery file from jquery site.

Add the following reference to the page where want to use the validation summary (the path can be different depending on how the downloaded folder is placed):

<script type=”text/javascript” src=”JQuery/jquery-1.4.1-vsdoc.js”></script>

<script type=”text/javascript” src=”ValidationSummary/ValidationSummary.js” />

<link rel=”Stylesheet” href=”ValidationSummary/ValidationSummary.css” />

Then add the validation control code as below:

<div id=”divValidationSummary”>

<asp:Label ID=”lblErrorSummaryHeader” runat=”server” Text=”Please resolve the following errors to proceed :”

CssClass=”hideValidationError”>

</asp:Label>

<ul>

<asp:RequiredFieldValidator ID=”rv1″

runat=”server” ControlToValidate=”txt1″>

<li>Error message</li>

</asp:RequiredFieldValidator>

<asp:RequiredFieldValidator ID=”rv2″

runat=”server” ControlToValidate=”txt2″>

<li>Error message</li>

</asp:RequiredFieldValidator>

……………………………..

……………………………..

……………………………..

……………………………..

……………………………..

<asp:RequiredFieldValidator ID=”rvn”

runat=”server” ControlToValidate=”txtn”>

<li>Error message</li>

</asp:RequiredFieldValidator>

</ul>

</div>

Here the RequiredFieldValidator controls ControlToValidate property will contain the controls Id whose validation message have to shown in the validation summary. And the ‘Error message’ is the error message that would be shown.

Here only RequiredFieldValidator is shown, its possible to add any other validation including regular expression validation and others.

Validation summary control in Action:

 The section is intended to show practical use of the validation summary control.

Form to validate

Form to validate

The use of validation summary control to validate the above form is given below:

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >

<head runat=”server”>

<title></title>

<script type=”text/javascript” src=”JQuery/jquery-1.4.1-vsdoc.js”></script>

<script type=”text/javascript” src=”ValidationSummary/ValidationSummary.js” />

<link rel=”Stylesheet” href=”ValidationSummary/ValidationSummary.css” />

<script type=”text/javascript”>

$(document).ready(function () {

var lblErrorSummaryHeaderClientID = ‘<%= lblErrorSummaryHeader.ClientID %>’;

$(“input[type=text]”).change(function () {

validation(lblErrorSummaryHeaderClientID);

});

$(‘#<%=btnSubmit.ClientID %>’).click(function () {

return validation(lblErrorSummaryHeaderClientID);

});

});

</script>

<style type=”text/css”>

</style>

</head>

<body>

<form id=”form1″ runat=”server”>

<div id=”divValidationSummary”>

<asp:Label ID=”lblErrorSummaryHeader” runat=”server” Text=”Please   resolve the following errors to proceed :” CssClass=”hideValidationError”>

</asp:Label>

<ul>

<asp:RequiredFieldValidator ID=”rv2FirstName”

runat=”server” ControlToValidate=”txtFirstName”>

<li>Enter First Name</li>

</asp:RequiredFieldValidator>

<asp:RequiredFieldValidator ID=”rv2LastName”

runat=”server” ControlToValidate=”txtLastName”>

<li>Enter Last Name</li>

</asp:RequiredFieldValidator>

<asp:RequiredFieldValidator ID=”rv2Address”

runat=”server” ControlToValidate=”txtAddress”>

<li>Enter Address</li>

</asp:RequiredFieldValidator>

</ul>

</div>

<div>

<table>

<tr>

<td>

First Name

</td>

<td style=”width:5px”></td>

<td>

<asp:TextBox ID=”txtFirstName” runat=”server”></asp:TextBox></td>

<td>

<asp:RequiredFieldValidator ID=”rv1FirstName” runat=”server” ControlToValidate=”txtFirstName”>*

</asp:RequiredFieldValidator>

</td>

</tr>

<tr>

<td style=”height:5px” colspan=”4″></td>

</tr>

<tr>

<td>

Last Name

</td>

<td style=”width:5px”></td>

<td>

<asp:TextBox ID=”txtLastName” runat=”server”></asp:TextBox>

</td>

<td>

<asp:RequiredFieldValidator ID=”rv1LastName” runat=”server”    ControlToValidate=”txtLastName”>*

</asp:RequiredFieldValidator>

</td>

</tr>

<tr>

<td style=”height:5px” colspan=”4″>

</td>

</tr>

<tr>

<td>

Address

</td>

<td style=”width:5px”></td>

<td><asp:TextBox ID=”txtAddress” runat=”server”></asp:TextBox></td>

<td>

<asp:RequiredFieldValidator ID=”rv1Address”

runat=”server” ControlToValidate=”txtAddress”>*

</asp:RequiredFieldValidator>

</td>

</tr>

<tr>

<td colspan=”2″>

&nbsp;

</td>

<td colspan=”2″>

<asp:Button runat=”server” ID=”btnSubmit” Text=”Submit” />

</td>

</tr>

</table>

</div>

</form>

</body>

</html>

Using the above code the form validation summary will be updated on every change in the text boxes and clicking on the submit button.

Use of AutoEventWireup property


When creating asp.net web page, in the html view there is AutoEventWireup=true what does it means.

It indicates that page event automatically binds with event handlers.

<%@ 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”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
    <title></title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <asp:TextBox ID=”txtPageLoadEventHandler” runat=”server”></asp:TextBox>
        <asp:TextBox ID=”txtButtonClickEventHandler” runat=”server”></asp:TextBox>
        <asp:Button ID=”btnTest” runat=”server” Text=”Button” onclick=”btnTest_Click” />
        </div>
    </form>
</body>
</html>

If the btnTest is clicked then the event handlers automatically called. as AutoEventWireup=”true”.


public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
txtPageLoadEventHandler.Text = "Inside Page_Load event handler";
}
protected void btnTest_Click(object sender, EventArgs e)
{
txtButtonClickEventHandler.Text = "Inside btnTest_Click event handler";
}
}

Now if use the same code above with AutoEventWireup=”false”. It shows that button click handler is called but page load is not called.

Now to call page load event handler event when AutoEventWireup=”false”. Have to explicitly bind the page load event with page load event handler like below :


public partial class _Default : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Page.Load+=new EventHandler(Page_Load);
}

protected void Page_Load(object sender, EventArgs e)
{
txtPageLoadEventHandler.Text = “Inside Page_Load event handler”;
}
protected void btnTest_Click(object sender, EventArgs e)
{
txtButtonClickEventHandler.Text = “Inside btnTest_Click event handler”;

}
}

How to get output from stored procedure using ASP.Net


Few days ago found a member in ASP.Net forum complaining about, he don’t found any clear example to get stored procedure output parameter from c# code in the internet.

So I provide him the code and think to write it here ,For helping others. Its very straight forward I am giving the stored procedure here it will help to understand how to write storedprocedure to return output:

Create procedure PROC_ReturnValue
(
@id int,
@Name_Id varchar(100) Output
)
As

set @Name_Id=(Select (Convert(varchar(20),id)+name)
from Items where id=@id)

And the following c# code shows how to call the storedprocedure along with the parameter(also the output parameter). And after execution  of the stored procedure how to get the output value:

C# Code :

SqlConnection cn = new SqlConnection(“data source=dbServerName;database=dbTest;uid=admin;pwd=Pass@123”);
SqlCommand cm = new SqlCommand();
cm.Connection = cn;

cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = “PROC_ReturnValue”;
cm.Parameters.AddWithValue(“@id”, 6);

     //Adding the output parameter
        cm.Parameters.AddWithValue(“@Name_Id”,string.Empty);
        cm.Parameters[1].SqlDbType = SqlDbType.VarChar;
        cm.Parameters[1].Direction = ParameterDirection.Output;
        cm.Parameters[1].Size = 100;

cn.Open();

SqlDataReader dr= cm.ExecuteReader();

        //Accessing the output parameter value

      string sOutPut= cm.Parameters[1].value;
cn.Close();

How to dynamically add template field of type textbox in ASP.Net gridview / How to get value from dynamically added template field of type textbox


I was working to make a utility tool to use for myself. This required having a gridview where user will input data and save. Here the no of input columns to be added was not fixed and was depends on some calculation at runtime. So I decided to dynamically add template field of type textbox in the gridview and save the user input when clicking save button.

I would describe the process that I followed to achieve this task in below:

The UI code is like below:

<div style=”padding-left: 20px; float: left”>
        <div style=”float: left; width: 100px; padding-top: 5px”>
            Formula</div>
        <div style=”float: left”>
            <asp:DropDownList ID=”drpFormula” runat=”server” OnSelectedIndexChanged=”drpFormula_SelectedIndexChanged”>
            </asp:DropDownList>
        </div>
        <div style=”padding-top: 5px”>
            <asp:Button ID=”btnSave” Width=”100px” runat=”server” Text=”Save” OnClick=”btnSave_Click” />
        </div>
        <div style=”height: 30px”>
        </div>
        <div style=”text-align: center; background-color: #F0F8FF;”>
            <b>List of Member and Attribute mapping</b></div>
        <div style=”padding-top: 20px”>
        </div>
        <asp:GridView ID=”gvMemberAttributeMap” runat=”server” EmptyDataText=”No Data Found”
            AutoGenerateColumns=”False” CellPadding=”4″ ForeColor=”#333333″ Width=”525px”
            ShowHeaderWhenEmpty=”True”>
            <AlternatingRowStyle BackColor=”White” ForeColor=”#284775″ />
            <EditRowStyle BackColor=”#999999″ />
            <FooterStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
            <HeaderStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
            <PagerStyle BackColor=”#284775″ ForeColor=”White” HorizontalAlign=”Center” />
            <RowStyle BackColor=”#F7F6F3″ ForeColor=”#333333″ />
            <SelectedRowStyle BackColor=”#E2DED6″ Font-Bold=”True” ForeColor=”#333333″ />
            <SortedAscendingCellStyle BackColor=”#E9E7E2″ />
            <SortedAscendingHeaderStyle BackColor=”#506C8C” />
            <SortedDescendingCellStyle BackColor=”#FFFDF8″ />
            <SortedDescendingHeaderStyle BackColor=”#6F8DAE” />
        </asp:GridView>
    </div>

Now whenever user chooses a formula, I have added columns and data in following way:

New template object added like below:

public class GridViewTemplate : ITemplate
{
//A variable to hold the type of ListItemType.
ListItemType _templateType;

//A variable to hold the column name.
string _columnName;

//Constructor where we define the template type and column name.
public GridViewTemplate(ListItemType type, string colname)
{
//Stores the template type.
_templateType = type;

//Stores the column name.
_columnName = colname;
}

void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
case ListItemType.Header:

//Creates a new label control and add it to the container.
Label lbl = new Label();            //Allocates the new label object.
lbl.Text = _columnName;             //Assigns the name of the column in the lable.
container.Controls.Add(lbl);        //Adds the newly created label control to the container.

break;

case ListItemType.Item:
//Creates a new text box control and add it to the container.
TextBox tb1 = new TextBox();                            //Allocates the new text box object.
//tb1.ID = “txtItem”;
tb1.DataBinding += new EventHandler(tb1_DataBinding);   //Attaches the data binding event.
tb1.Columns = 4;                                        //Creates a column with size 4.

container.Controls.Add(tb1);                            //Adds the newly created textbox to the container.

break;

case ListItemType.EditItem:
//Creates a new text box control and add it to the container.
TextBox tb2 = new TextBox();
//Allocates the new text box object.
tb2.DataBinding += new EventHandler(tb1_DataBinding);   //Attaches the data binding event.
tb2.Columns = 4;                                        //Creates a column with size 4.

container.Controls.Add(tb2);
//As, I am not using any EditItem, I didnot added any code here.
break;

case ListItemType.Footer:

CheckBox chkColumn = new CheckBox();
chkColumn.ID = “Chk” + _columnName;
container.Controls.Add(chkColumn);

break;

}

}

/// <summary>
/// This is the event, which will be raised when the binding happens.
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>
void tb1_DataBinding(object sender, EventArgs e)
{
TextBox txtdata = (TextBox)sender;
GridViewRow container = (GridViewRow)txtdata.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _columnName);

if (dataValue != DBNull.Value)
{
txtdata.Text = dataValue.ToString();
}
}

}

Gridview with the above template filed loads by the following way:

         /// <summary>
        /// Selected index change event handler for formula
        /// </summary>
        /// <param name=”sender”></param>
        /// <param name=”e”></param>
        protected void cmbFormula_SelectedIndexChanged(object sender, EventArgs e)
        {
            Guid gFormulaId = new Guid(cmbFormula.SelectedValue);
            BindDataToGrid(gFormulaId);
        }

        /// <summary>
        /// This method load the Gridview for the selected formula
        /// </summary>
        /// <param name=” gFormulaId”></param>
        void BindDataToGrid(Guid gFormulaId)
        {
            DataTable dt = DistributionManagement.GetAllMemberAttributeMapForFormula(gFormulaId);

            int i = 1;

            gvMemberAttributeMap.Columns.Clear();

            foreach (DataColumn dc in dt.Columns)
            {
                TemplateField tempField = new TemplateField();
                tempField.HeaderTemplate = new GridViewTemplate(ListItemType.Header, dc.ColumnName);
                tempField.ItemTemplate = new GridViewTemplate(ListItemType.EditItem, dc.ColumnName);

                BoundField boundField = new BoundField();
                boundField.DataField = dc.ColumnName;
                boundField.HeaderText = dc.ColumnName;

                /*For even order column add the bound filed and hide that column*/
                if (i % 2 != 0)
                {
                    gvMemberAttributeMap.Columns.Add(boundField);
                    boundField.HeaderStyle.CssClass = “hide”;
                    boundField.ItemStyle.CssClass = “hide”;

                }
                /*For odd order(including the first) column add the template filed*/
                else
                {
                    if (i == 2)
                    {
                        gvMemberAttributeMap.Columns.Add(boundField);
                    }
                    else
                    {
                        gvMemberAttributeMap.Columns.Add(tempField);
                    }
                }

                i++;
            }

            gvMemberAttributeMap.DataSource = dt;
            gvMemberAttributeMap.DataBind();

            Session[“CurrentSource”] = dt;

        }

        /// <summary>
        /// Save button click event handler
        /// </summary>
        /// <param name=”sender”></param>
        /// <param name=”e”></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Guid gFormulaId = new Guid(cmbFormula.SelectedValue);

            List<MemberAttributeMapp> lstMemberAttributeMap = new List<MemberAttributeMapp>();
            MemberAttributeMapp oMemberAttributeMap = null;

            if (gFormulaId.Equals(Guid.Empty))
            {
                return;
            }

           // BindDataToGrid(gFormulaId);

            foreach (GridViewRow gRow in gvMemberAttributeMap.Rows)
            {
                int iNoOfAttribute = gRow.Cells.Count;
                Guid gMemberId = new Guid(gRow.Cells[0].Text);

                for (int i = 2; i < iNoOfAttribute; i += 2)
                {
                    oMemberAttributeMap = new MemberAttributeMapp();
                    oMemberAttributeMap.ID = Guid.NewGuid();
                    oMemberAttributeMap.FormulaId = gFormulaId;
                    oMemberAttributeMap.MemberId = gMemberId;

                    oMemberAttributeMap.AttributeId = new Guid(gvMemberAttributeMap.Columns[i].HeaderText);
                    oMemberAttributeMap.Weight = Convert.ToDecimal(((System.Web.UI.WebControls.TextBox)gRow.Cells[i+1].Controls[0]).Text);

                    lstMemberAttributeMap.Add(oMemberAttributeMap);
                }

            }

            DistributionManagement.SaveAllMemberAttributeMapForFormula(lstMemberAttributeMap, gFormulaId);

            BindDataToGrid(gFormulaId);
        }

 Now Gridview loads successfully upon selected index change of formula dropdown.

GridView view after adding dynamic template field of textbox type

But when clicking the save button it throws exception in the line

oMemberAttributeMap.Weight = Convert.ToDecimal(((System.Web.UI.WebControls.TextBox)gRow.Cells[i+1].Controls[0]).Text);

 And upon debugging I found that it doesn’t contains the added template TextBox control.

Try lots of different way and found the addition of CreateChildControls() event solves my problem and it work fine. The CreateChildControls() is like below for my task :

/*Addds columns and Binds the gridview with the current session data*/

 protected override void CreateChildControls()
        {
            base.CreateChildControls();

            if (Session[“CurrentSource”] != null && !cmbFormula.SelectedValue.Equals(Guid.Empty.ToString()))
            {
                DataTable dt = (DataTable)Session[“CurrentSource”];

                gvMemberAttributeMap.Columns.Clear();
                int i = 1;

                foreach (DataColumn dc in dt.Columns)
                {
                    TemplateField tempField = new TemplateField();
                    tempField.HeaderTemplate = new GridViewTemplate(ListItemType.Header, dc.ColumnName.TrimEnd());
                    tempField.ItemTemplate = new GridViewTemplate(ListItemType.EditItem, dc.ColumnName.TrimEnd());

                    BoundField boundField = new BoundField();
                    boundField.DataField = dc.ColumnName;
                    boundField.HeaderText = dc.ColumnName;

                    if (i % 2 != 0)
                    {
                        gvMemberAttributeMap.Columns.Add(boundField);
                        boundField.HeaderStyle.CssClass = “hide”;
                        boundField.ItemStyle.CssClass = “hide”;

                    }
                    else
                    {
                        if (i == 2)
                        {
                            gvMemberAttributeMap.Columns.Add(boundField);
                        }
                        else
                        {
                            gvMemberAttributeMap.Columns.Add(tempField);
                        }
                    }

                    i++;
                }

                gvMemberAttributeMap.DataSource = dt;
                gvMemberAttributeMap.DataBind();
            }