Wednesday, November 2, 2011

SSL Certificate creation on IIS web server

Thursday, October 27, 2011

GRIDVIEW EVENTS IN ASP.NET with C#

GridView is the most reused tool in ASP.NET. This gridview contains 7 major events which are always used in every situation.
  1. grdGroups_PageIndexChanging
  2. grdGroups_RowDeleting
  3. grdGroups_RowEditing
  4. grdGroups_RowCancelingEdit
  5. grdGroups_RowUpdating
  6. grdGroups_RowCommand
  7. grdGroups_Sorting



All the above events are web server events which are coded as below

//This PageIndexChanging event is used for navigating from one page to another page. Here page means set //of records. Each page contains count of records. The page size is defined in code behind.

protected void grdGroups_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                grdGroups.PageIndex = e.NewPageIndex;
                GetGroups();
            }
            catch (Exception ex)
            {
                Throw ex;
            }
        }


//This RowDeleting Event is used for deleting a single record at a time. 

        protected void grdGroups_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                objGrp.GroupID = Convert.ToInt32(Session["GroupID"].ToString());
                objGrp.UserID = Convert.ToInt32(Session["loginid"].ToString());
                objGrp.DeleteGroup();// This method contains original logic for deleting the record.
                GetGroups();
            }
            catch (Exception ex)
            {
               Throw ex;
            }
        }
//RowEditing Event is used for setting up the selected record in edit mode.

        protected void grdGroups_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
                grdGroups.EditIndex = e.NewEditIndex;
                GetGroups();
            }
            catch (Exception ex)
            {
               Throw ex;
            }
        }

//CancelEdit Event is used for reset the selected record from edit mode.
        protected void grdGroups_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                grdGroups.EditIndex = -1;
                GetGroups();
            }
            catch (Exception ex)
            {
               Throw ex;
            }
        }

//After Edit the selected record values, this RowUpdating Event is used to update the edited values.

        protected void grdGroups_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                TextBox txt = (TextBox)grdGroups.Rows[e.RowIndex].FindControl("txtgroupName");
                grdGroups.EditIndex = -1;
                objGrp.GroupName = txt.Text.Trim();
                objGrp.GroupID = Convert.ToInt32(Session["GroupID"].ToString());
                objGrp.UserID = Convert.ToInt32(Session["loginid"].ToString());
                objGrp.UpdateGroup(); // This method contains original logic to update the record on database.
                GetGroups();
            }
            catch (Exception ex)
            {
                Throw ex;
            }
        }

//This event is used for external purposes like button click events inside a grid.
        protected void grdGroups_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName.ToString() == "Update")
                {
                    Session["GroupID"] = e.CommandArgument.ToString();
                }
                if (e.CommandName.ToString() == "Delete")
                {
                    Session["GroupID"] = e.CommandArgument.ToString();
                }
            }
            catch (Exception ex)
            {
               throw ex;
            }
        }

//Row_Sorting Event is used for sorting the record by selecting the column.

        protected void grdGroups_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                DataTable dt = ((DataSet)ViewState["GroupList"]).Tables[0];
                dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
                grdGroups.DataSource = dt;
                grdGroups.DataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


 private void GetGroups()
        {
            try
            {
                objGrp.UserID = Convert.ToInt32(Session["loginid"].ToString());
                DataSet ds = objGrp.GetGroupsbyUser();
                ViewState["GroupList"] = ds;
                if (ds.Tables[0].Rows.Count > 0)
                {
                    grdGroups.DataSource = ds.Tables[0];
                    grdGroups.DataBind();
                }
                else
                {
                   // Below code is used for displaying some text if there is no record to bind to grid.
                    ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                    grdGroups.DataSource = ds;
                    grdGroups.DataBind();
                    int columnscount = grdGroups.Columns.Count;
                    grdGroups.Rows[0].Cells.Clear();
                    grdGroups.Rows[0].Cells.Add(new TableCell());
                    grdGroups.Rows[0].Cells[0].ColumnSpan = columnscount;
                    grdGroups.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
                    grdGroups.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Red;
                    grdGroups.Rows[0].Cells[0].Font.Bold = true;
                    grdGroups.Rows[0].Cells[0].Text = "No Groups List";
                }
            }
            catch (Exception ex)
            {
                Throw ex;
            }
        }


//This method is used in Row_Sorting Event.
private string GetSortDirection(string column)
        {

            // By default, set the sort direction to ascending.
            string sortDirection = "ASC";

            // Retrieve the last column that was sorted.
            string sortExpression = ViewState["SortExpression"] as string;

            if (sortExpression != null)
            {
                // Check if the same column is being sorted.
                // Otherwise, the default value can be returned.
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }

            // Save new values in ViewState.
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;

            return sortDirection;
        }       


Code Behind

 <asp:GridView ID="grdGroups" runat="server" AutoGenerateColumns="false"
                CssClass="GridStyle" AllowPaging="True"
        onpageindexchanging="grdGroups_PageIndexChanging"
        onrowcancelingedit="grdGroups_RowCancelingEdit"
        onrowdeleting="grdGroups_RowDeleting" onrowediting="grdGroups_RowEditing"
        onrowupdating="grdGroups_RowUpdating" PageSize="5" Width="70%"
            onrowcommand="grdGroups_RowCommand" onsorting="grdGroups_Sorting" AllowSorting="true">
        <Columns>
        <asp:TemplateField>
        <ItemTemplate>
            <asp:CheckBox ID="CheckBoxSelect" runat="server" Enabled="false"/>
        </ItemTemplate>
        <EditItemTemplate>
        <asp:CheckBox ID="CheckBoxSelect" runat="server" Enabled="false"/>
        </EditItemTemplate>
        </asp:TemplateField>    
         <asp:TemplateField HeaderText="GroupName" HeaderStyle-Width="250px" SortExpression="groupname">
        <ItemTemplate>      
        <%#Eval("groupname")%>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="txtgroupName" runat="server" CssClass="controlStyle" Text='<%#Eval("groupname")%>' MaxLength="20">
            </asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
            ErrorMessage="! Enter group Name" ControlToValidate="txtgroupName" ValidationGroup="G" Text="!!">
            </asp:RequiredFieldValidator>
        </EditItemTemplate>

        </asp:TemplateField>  
        <asp:TemplateField HeaderText="Edit" HeaderStyle-Width="150px" SortExpression="GroupID">
        <ItemTemplate>
            <asp:LinkButton ID="lnkGroupEdit" runat="server" CommandName="Edit" ToolTip="Edit this Group"
            Text="Edit"></asp:LinkButton>      
        </ItemTemplate>
        <EditItemTemplate>
        <asp:LinkButton ID="lnkGroupUpdate" runat="server" CommandArgument='<%#Eval("GroupID")%>' CommandName="Update"
            Text="Update" ValidationGroup="G" ToolTip="Update"></asp:LinkButton>
            <asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel"
            Text="Cancel"></asp:LinkButton>
            <asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="true" ShowSummary="false" ValidationGroup="G"/>
        </EditItemTemplate>

        </asp:TemplateField>  
         <asp:TemplateField HeaderText="Delete">
        <ItemTemplate>
            <asp:LinkButton ID="lnkGroupDelete" runat="server" CommandArgument='<%#Eval("GroupID")%>' CommandName="Delete" Text="Delete"
             ToolTip="Delete this Group" OnClientClick="javascript:return confirm('If you delete this Group, all Contacts of this Group Also Deleted,Are you sure you want to delete this Item?');"></asp:LinkButton>      
        </ItemTemplate>
        <EditItemTemplate>      
        </EditItemTemplate>
        </asp:TemplateField>
        </Columns>
        <HeaderStyle CssClass="GridHeader" />
        <AlternatingRowStyle CssClass="GridAlter" />
        <RowStyle CssClass="gridrowstyle" />
        <PagerStyle CssClass="GridPager" />      
        </asp:GridView>  

Thursday, September 8, 2011

HOW TO OPEN POPUP USING JAVASCRIPT


<a href="#" onclick="OpenWindow()">Insert Data
<script language="javascript" type="text/javascript"> function OpenWindow() { window.open ("PopUpWindow.aspx", "mywindow", "menubar=0,resizable=0," + "width=350,height=250,toolbars=0"); } </script>

Thursday, August 11, 2011

Set status bar text using asp.net


 protected void Page_Load(object sender, EventArgs e)
        {         
            // Create a message string
            string strMessage = "This is a message in status bar";
            // Register startup script to show a message in status bar
            this.RegisterStartupScript("SetStatusText", "<script>window.status='" +
                strMessage + "';</script>");
        }

How to prevent visiting pages from History after Logout


After having successfully logged-in to an application, you are redirected to the next page (say Home.aspx) which is a content page of master page (say Master.master). In this master page you have a link for logout. When you click on the logout button it redirects you to the Login page (provided this is not the content page of Master.master). Now if you click on the back arrow of browser then it goes to the previous page. To avoid this, the following code can be used in your master page where the logout button is present.
 Design a login page, give user name and password then redirect to some other page which is a content page of a Master page. In this master page one link button should be present for logout. When you click on the logout button it redirects to the login page. Then when you click on the back arrow of the browser it again goes to the previous page (that you already visit before logout). Even if you write code for session clear in logout button click event still it goes to previous page. To avoid this write few lines of code in Page_Init method of master page.
  protected void Page_Init(object sender, EventArgs e)
{
      Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
      Response.Cache.SetCacheability(HttpCacheability.NoCache);
      Response.Cache.SetNoStore();
}
 
 
Following is the full code for master page where logout button is present.
Master.master
<asp:LinkButton ID="lnkLogout" runat="server" Text="logout"onclick="lnkLogout_Click"></asp:LinkButton>
Master.master.cs
protected void Page_Init(object sender, EventArgs e)
{
      Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
      Response.Cache.SetCacheability(HttpCacheability.NoCache);
      Response.Cache.SetNoStore();
}
protected void Page_Load(object sender, EventArgs e)
{
      long userId = Convert.ToInt64(Session["UserId"]);
      if(!IsPostBack)
      {
            if(userId == 0)
            {
                  Response.Redirect("Login.aspx");
            }
      }
}
protected void lnkLogout_Click(object sender, EventArgs e)
{
      Session.Clear();
      Session.Abandon();
      Response.Redirect("Login.aspx");
 
}
 
N.B:- Login page was not a content page of Master page (which contains the logout button).

Tuesday, July 26, 2011

HOW to Install/Uninstall Windows Service

To Install a Windows Service, We can use either a .NET Command Prompt, or DOS Command Prompt.

By using .NET Command Prompt,

goto the directory where Service is located,
type installutil <servicename.exe>, to uninstall, type  installutil /u <servicename.exe>

By Using DOS Command Prompt,

If .NET is not installed in your application, then to install this windows service, must needs .net framework.

goto the directory where installutil.exe is exists.
(by default, in server machines, it is in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727)

in DOS Command prompt, goto that path, and then type installutil C:/services/servicename.exe
(give complete path and name of service to install, same to unsintsall.)

Thursday, May 19, 2011

HOW TO DELETE WINDOWS SERVICE MANUALLY

Goto Command Prompt and Type 'RegEdit'


and Navigate As Follows : 
My Computer >> HKEY_LOCAL_MACHINE >> SYSTEM >> CurrentControlSet >> Services


Wednesday, March 30, 2011

Windows XP Run Command List



  1. Accessibility Controls – access.cpl
  2. Accessibility Wizard – accwiz
  3. Add Hardware – Wizardhdwwiz.cpl
  4. Add/Remove Programs – appwiz.cpl
  5. Administrative Tools control – admintools
  6. Adobe Acrobat (if installed) – acrobat
  7. Adobe Designer (if installed)- acrodist
  8. Adobe Distiller (if installed)- acrodist
  9. Adobe ImageReady (if installed)- imageready
  10. Adobe Photoshop (if installed)- photoshop
  11. Automatic Updates – wuaucpl.cpl
  12. Bluetooth Transfer Wizard – fsquirt
  13. Calculator – calc
  14. Certificate Manager – certmgr.msc
  15. Character Map – charmap
  16. Check Disk Utility – chkdsk
  17. Clipboard Viewer – clipbrd
  18. Command Prompt – cmd
  19. Component Services – dcomcnfg
  20. Computer Management – compmgmt.msc
  21. Control Panel – control
  22. Date and Time Properties – timedate.cpl
  23. DDE Shares – ddeshare
  24. Device Manager – devmgmt.msc
  25. Direct X Control Panel (If Installed)- directx.cpl
  26. Direct X Troubleshooter- dxdiag
  27. Disk Cleanup Utility- cleanmgr
  28. Disk Defragment- dfrg.msc
  29. Disk Management- diskmgmt.msc
  30. Disk Partition Manager- diskpart
  31. Display Properties (w/Appearance Tab Preselected)- control color
  32. Display Properties- control desktop
  33. Display Properties- desk.cpl
  34. Dr. Watson System Troubleshooting Utility- drwtsn32
  35. Driver Verifier Utility- verifier
  36. Event Viewer- eventvwr.msc
  37. File Signature Verification Tool- sigverif
  38. Files and Settings Transfer Tool- migwiz
  39. Findfast- findfast.cpl
  40. Firefox (if installed)- firefox
  41. Folders Properties- control folders
  42. Fonts- control fonts
  43. Fonts Folder- fonts
  44. Free Cell Card Game- freecell
  45. Game Controllers- joy.cpl
  46. Group Policy Editor (XP Prof)- gpedit.msc
  47. Hearts Card Game- mshearts
  48. Help and Support- helpctr
  49. HyperTerminal- hypertrm
  50. Iexpress Wizard- iexpress
  51. Indexing Service- ciadv.msc
  52. Internet Connection Wizard- icwconn1
  53. Internet Explorer- iexplore
  54. Internet Properties- inetcpl.cpl
  55. Internet Setup Wizard- inetwiz
  56. IP Configuration (Delete DNS Cache Contents)- ipconfig /flushdns
  57. IP Configuration (Display Connection Configuration) – ipconfi/all
  58. IP Configuration (Display DHCP Class ID)- ipconfig/showclassid
  59. IP Configuration (Display DNS Cache Contents)- ipconfig /displaydns
  60. IP Configuration (Modifies DHCP Class ID)- ipconfig /setclassid
  61. IP Configuration (Release All Connections)- ipconfig /release
  62. IP Configuration (Renew All Connections)- ipconfig /renew
  63. IP Configuration(RefreshesDHCP&Re-RegistersDNS)-ipconfig/registerdns
  64. Java Control Panel (If Installed)- javaws
  65. Java Control Panel (If Installed)- jpicpl32.cpl
  66. Keyboard Properties – control keyboard
  67. Local Security Settings – secpol.msc
  68. Local Users and Groups – lusrmgr.msc
  69. Logs You Out Of Windows – logoff…..
  70. Malicious Software Removal Tool – mrt
  71. Microsoft Access (if installed) – access.cpl
  72. Microsoft Chat – winchat
  73. Microsoft Excel (if installed) – excel
  74. Microsoft Frontpage (if installed)- frontpg
  75. Microsoft Movie Maker – moviemk
  76. Microsoft Paint – mspaint
  77. Microsoft Powerpoint (if installed)- powerpnt
  78. Microsoft Syncronization Tool – mobsync
  79. Microsoft Word (if installed)- winword
  80. Minesweeper Game – winmine
  81. Mouse Properties – control mouse
  82. Mouse Properties – main.cpl
  83. Nero (if installed)- nero
  84. Netmeeting – conf
  85. Network Connections – control netconnections
  86. Network Connections – ncpa.cpl
  87. Network Setup Wizard – netsetup.cpl
  88. Notepad – notepad
  89. Nview Desktop Manager (If Installed)- nvtuicpl.cpl
  90. Object Packager – packager
  91. ODBC Data Source Administrator- odbccp32.cpl
  92. On Screen Keyboard – osk
  93. Opens AC3 Filter (If Installed) – ac3filter.cpl
  94. Outlook Express – msimn
  95. Paint – pbrush
  96. Password Properties – password.cpl
  97. Performance Monitor – perfmon.msc
  98. Phone and Modem Options – telephon.cpl
  99. Phone Dialer – dialer
  100. Pinball Game – pinball
  101. Power Configuration – powercfg.cpl
  102. Printers and Faxes – control printers
  103. Printers Folder – printers
  104. Private Character Editor – eudcedit
  105. Quicktime (If Installed)- QuickTime.cpl
  106. Real Player (if installed)- realplay
  107. Regional Settings – intl.cpl
  108. Registry Editor – regedit
  109. Registry Editor – regedit32
  110. Remote Access Phonebook – rasphone
  111. Remote Desktop – mstsc
  112. Removable Storage – ntmsmgr.msc
  113. Removable Storage Operator Requests – ntmsoprq.msc
  114. Resultant Set of Policy (XP Prof) – rsop.msc
  115. Scanners and Cameras – sticpl.cpl
  116. Scheduled Tasks – control schedtasks
  117. Security Center – wscui.cpl
  118. Services – services.msc
  119. Shared Folders – fsmgmt.msc
  120. Shuts Down Windows – shutdown
  121. Sounds and Audio – mmsys.cpl
  122. Spider Solitare Card Game – spider
  123. SQL Client Configuration – cliconfg
  124. System Configuration Editor – sysedit
  125. System Configuration Utility – msconfig
  126. System File Checker Utility (Purge File Cache)- sfc /purgecache
  127. System File Checker Utility (Return to Default Setting)- sfc /revert
  128. System File Checker Utility (Scan Immediately)- sfc /scannow
  129. System File Checker Utility (Scan On Every Boot) – sfc /scanboot
  130. System File Checker Utility (Scan Once At Next Boot)- sfc /scanonce
  131. System File Checker Utility (Set Cache Size to size x)-sfc/cachesize=x
  132. System Information – msinfo32.
  133. System Properties – sysdm.cpl
  134. Task Manager – taskmgr
  135. Task Manager – taskmgr
  136. TCP Tester – tcptest
  137. Telnet Client – telnet
  138. Tweak UI (if installed) – tweakui
  139. User Account Management- nusrmgr.cpl
  140. Utility Manager – utilman
  141. Windows Address Book – wab
  142. Windows Address Book Import Utility – wabmig
  143. Windows Backup Utility (if installed)- ntbackup
  144. Windows Explorer – explorer
  145. Windows Firewall- firewall.cpl
  146. Windows Magnifier- magnify
  147. Windows Management Infrastructure – wmimgmt.msc
  148. Windows Media Player – wmplayer
  149. Windows Messenger – msmsgs
  150. Windows Picture Import Wizard (need camera connected)- wiaacmgr
  151. Windows System Security Tool – syskey
  152. Windows Update Launches – wupdmgr
  153. Windows Version (to show which version of windows)- winver
  154. Windows XP Tour Wizard – tourstart
  155. Wordpad – write

Tuesday, March 29, 2011

GRID VIEW BINDING WITH TEMPLATE FIELDS DYNAMICALLY - ASP.NET with C#


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

namespace SomeName.Classes
{
    public class GridViewTemplate : ITemplate
    {
        private DataControlRowType templateType;
        private string columnName;
        private string columnNameBinding;
        private string controlType;
        private int ctrllength;

        public GridViewTemplate(DataControlRowType type, string colname, string colNameBinding, string ctlType,int length)
        {
            templateType = type;
            columnName = colname;
            columnNameBinding = colNameBinding;
            controlType = ctlType;
            ctrllength = length;
        }

        public void InstantiateIn(System.Web.UI.Control container)
        {
            switch (templateType)
            {
                case DataControlRowType.Header:
                    Literal lc = new Literal();
                    lc.Text = columnName;
                    container.Controls.Add(lc);
                    break;
                case DataControlRowType.DataRow:
                    if (controlType == "Label")
                    {
                        Label lb = new Label();

                        lb.ID = "lbl_" + columnNameBinding;
                        lb.DataBinding += new EventHandler(this.ctl_OnDataBinding);
                        container.Controls.Add(lb);
                    }
                    else if (controlType == "TextBox")
                    {
                        TextBox tb = new TextBox();
                        tb.ID = "tb" + columnNameBinding;
                        tb.DataBinding += new EventHandler(this.ctl_OnDataBinding);
                        tb.Width = ctrllength;
                        container.Controls.Add(tb);
                    }
                    else if (controlType == "CheckBox")
                    {
                        CheckBox cb = new CheckBox();
                        cb.ID = "cb1" + columnNameBinding;
                        cb.DataBinding += new EventHandler(this.ctl_OnDataBinding);
                        container.Controls.Add(cb);
                    }
                    else if (controlType == "HyperLink")
                    {
                        HyperLink hl = new HyperLink();
                        hl.ID = "hl1";
                        hl.DataBinding += new EventHandler(this.ctl_OnDataBinding);
                        container.Controls.Add(hl);
                    }
                    else if (controlType == "HiddenField")
                    {
                        HiddenField hf = new HiddenField();
                        hf.ID = "hf" + columnNameBinding;
                        hf.DataBinding += new EventHandler(this.ctl_OnDataBinding);
                        container.Controls.Add(hf);
                    }
                    break;
                default:
                    break;
            }
        }

        public void ctl_OnDataBinding(object sender, EventArgs e)
        {
            if (sender.GetType().Name == "Label")
            {
                Label lb = (Label)sender;
                GridViewRow container = (GridViewRow)lb.NamingContainer;
                lb.Text = ((DataRowView)container.DataItem)[columnNameBinding].ToString();
            }
            else if (sender.GetType().Name == "TextBox")
            {
                TextBox tb = (TextBox)sender;
                GridViewRow container = (GridViewRow)tb.NamingContainer;
                tb.Text = ((DataRowView)container.DataItem)[columnNameBinding].ToString();
            }
            else if (sender.GetType().Name == "CheckBox")
            {
                CheckBox cb = (CheckBox)sender;
                GridViewRow container = (GridViewRow)cb.NamingContainer;
                cb.Checked = Convert.ToBoolean(((DataRowView)container.DataItem)[columnNameBinding].ToString());
            }
            else if (sender.GetType().Name == "HyperLink")
            {
                HyperLink hl = (HyperLink)sender;
                GridViewRow container = (GridViewRow)hl.NamingContainer;
                hl.Text = ((DataRowView)container.DataItem)[columnNameBinding].ToString();
                hl.NavigateUrl = ((DataRowView)container.DataItem)[columnNameBinding].ToString();
            }
            else if (sender.GetType().Name == "HiddenField")
            {
                HiddenField hf = (HiddenField)sender;
                GridViewRow container = (GridViewRow)hf.NamingContainer;
                hf.Value  = ((DataRowView)container.DataItem)[columnNameBinding].ToString();
            }
        }
    }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////Place the above class seperately and
//////////////Use the Following code in aspx.cs,
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 string strColName="Some DaField Column Name";
                string strColLabel = "Header text";
  TemplateField tField = new TemplateField();
                tField.HeaderText = strColLabel;
                tField.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, strColLabel, strColName, "", 0);
                if (Some Condition) 
                    tField.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, "", strColName, "Label", 100);
                else
                    tField.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, "",strColName, "TextBox", 100);
                grdMapValues.Columns.Add(tField);
            }
            if (dtMapData.Rows.Count > 0)
            {               
                grdMapValues.DataSource = dtMapData;              
                grdMapValues.DataBind();
            }

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////In Code Behind, the Gridview is like this
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


<asp:GridView ID="grdname" runat="server"
 CssClass="GridStyle" ShowHeader="true" AutoGenerateColumns="false">
   <Columns>
    <asp:TemplateField><ItemTemplate></ItemTemplate></asp:TemplateField>
   </Columns>
</asp:GridView>