Saturday, March 26, 2011

GridView makeover using CSS

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

//http://atashbahar.com/post/GridView-makeover-using-CSS.aspx
public partial class StylishGridView_Demo_GridViewMakeOver : System.Web.UI.Page
{
    CustomersDataObject objData = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            objData = new CustomersDataObject();
            //DataTable dt =  objData.Select().Table ;
            gvStylish.DataSource = objData.Select();
            gvStylish.DataBind();
        }
    }

    protected void gvStylish_Sorting(object sender, GridViewSortEventArgs e)
    {
        //Change sort direction
        SortDirection = SortDirection == SortDirection.Descending ? SortDirection.Ascending : SortDirection.Descending;
        string sSortExpression = SortDirection == SortDirection.Ascending ? " Asc" : " Desc";

        //If new column, set as asc
        if (Convert.ToString(SortExpression) != e.SortExpression)
        {
            SortDirection = SortDirection.Ascending;
            sSortExpression = " Asc";
        }

        sSortExpression = e.SortExpression + sSortExpression;
        SortExpression = e.SortExpression;

        objData = new CustomersDataObject();
        gvStylish.DataSource = new DataView(objData.Select().Table, string.Empty, sSortExpression, DataViewRowState.CurrentRows);
        gvStylish.DataBind();
    }

    protected void gvStylish_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        objData = new CustomersDataObject();
        //DataTable dt =  objData.Select().Table ;
        gvStylish.PageIndex = e.NewPageIndex;
        gvStylish.DataSource = objData.Select();
        gvStylish.DataBind();
    }

    protected void gvStylish_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridView gridView = (GridView)sender;

        //You have to set the SortExpression in the aspx page.
        if (e.Row.RowType == DataControlRowType.Header)
        {
            //To add tooltip for the header
            if (e.Row.RowType == DataControlRowType.Header)
            {
                foreach (TableCell cell in e.Row.Cells)
                {
                    foreach (Control ctl in cell.Controls)
                    {
                        if (ctl.GetType().ToString().Contains("DataControlLinkButton"))
                        {
                            cell.Attributes.Add("title", "Click to sort " + ((LinkButton)ctl).Text);
                        }
                    }
                }
            }

            //Set default header style for the gridview
            //Get sorted column index for the templated gridview
            SortIndex = -1;
            foreach (DataControlField field in gridView.Columns)
            {
                e.Row.Cells[gridView.Columns.IndexOf(field)].CssClass = "sortable";

                if (!string.IsNullOrEmpty(SortExpression))
                {
                    if (field.SortExpression == SortExpression)
                    {
                        SortIndex = gridView.Columns.IndexOf(field);
                    }
                }
            }

            //Set Sorted style for the gridview header
            if (SortIndex > -1)
                e.Row.Cells[SortIndex].CssClass = (SortDirection == SortDirection.Ascending
                                            ? " sortable sorted asc" : " sortable sorted desc");
        }
        else if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //To change color for the sorded gridvew entire column
            if (SortIndex > -1)
                e.Row.Cells[SortIndex].CssClass += (e.Row.RowIndex % 2 == 0 ? " sortaltrow" : "sortrow");

            //#region Add toolTip to the asp:CommandField Starts
            //int lastCell = e.Row.Cells.Count - 1;
            //foreach (Control ctrl in e.Row.Cells[lastCell].Controls)
            //{
            //    if (ctrl.GetType().BaseType.Name == "LinkButton")
            //    {
            //        LinkButton lnkBtn = ctrl as LinkButton;

            //        switch (lnkBtn.Text.Trim())
            //        {
            //            case "Edit":
            //                lnkBtn.ToolTip = "Click to edit the record.";
            //                break;

            //            case "Delete":
            //                lnkBtn.Attributes.Add("onclick", "javascript:return confirm('Do you want to delete the selected Course?');");
            //                lnkBtn.ToolTip = "Click to delete the record.";
            //                break;
            //        }
            //    }
            //}
            //#endregion
        }
    }

    #region "Properties"
    public Int32 SortIndex
    {
        get
        {
            if (ViewState["_SortIndex_"] == null)
                ViewState["_SortIndex_"] = -1;

            return (Int32)ViewState["_SortIndex_"];
        }
        set { ViewState["_SortIndex_"] = value; }
    }

    public string SortExpression
    {
        get
        {
            if (ViewState["_SortExpression_"] == null)
                ViewState["_SortExpression_"] = string.Empty;

            return (string)ViewState["_SortExpression_"];
        }
        set { ViewState["_SortExpression_"] = value; }
    }

    public SortDirection SortDirection
    {
        get
        {
            if (ViewState["_SortDirection_"] == null)
                ViewState["_SortDirection_"] = SortDirection.Ascending;

            return (SortDirection)ViewState["_SortDirection_"];
        }
        set { ViewState["_SortDirection_"] = value; }
    }

    #endregion
}

#container /*make horizontal center of a div*/
{
 margin: 10px auto;
 width: 700px;
}
.mGrid
{
 background-color: #fff;
 border: solid 1px #525252;
 border-collapse: collapse;
 margin: 5px 0 10px 0;
 width: 100%;
 font: 11px Tahoma;
}

/*Header style starts*/
.mGrid tr th
{
 background: #424242 url(Images/grd_head.png) repeat-x top;
 border:0px;
 border-bottom: 1px solid #c1c1c1;
 border-right: 1px solid #c1c1c1;
 color: #fff;
 font-size: 0.9em;
 padding: 4px 2px;
}

/*Sorting Starts*/
.mGrid tr th.sortable
{
 padding: 0px;
}

.mGrid tr th.sortable:hover
{
 background: #b7e7fb url('Images/grid-header-sortable-back-hover.gif') top left repeat-x;
 border: 1px solid #C4C4C4;
 border-left: none;
 border-top: none;
}

.mGrid tr th.sortable a
{
 color: white;
 display: block;
 min-height: 1px;
 padding: 3px 3px 2px 2px;
 text-decoration: none;
}

.mGrid tr th.sortable a:hover
{
 text-decoration: none;
}

.mGrid tr th.sorted
{
 background: #d8ecf6 url('Images/grid-header-sorted-back.jpg') top left repeat-x;
 border: 1px solid #8B8878;
 border-left: none;
 border-top: none;
}

.mGrid tr th.asc a
{
 background: transparent url('Images/grid-header-asc-glyph.gif') center 1px no-repeat;
}

.mGrid tr th.desc a
{
 background: transparent url('Images/grid-header-desc-glyph.gif') center 1px no-repeat;
}
/*Sorting Ends*/

.mGrid tr .RowStyle
{
 border: 1px solid red;
 padding: 2px 6px 2px 4px;
}

.mGrid tr.alt
{
 background: #f2f9fc;
}

.mGrid tr.RowStyle:hover, .mGrid tr.alt:hover
{
 background: #c1c1c1 url(Images/grid-header-hover.gif) repeat-x top;
}


/*Select entire sorted column starts*/
.mGrid tr.RowStyle .sortaltrow, .mGrid tr.alt .sortaltrow 
{
    background-color: #D6D6D6;
}

.mGrid tr.RowStyle .sortrow, .mGrid tr.alt .sortrow 
{
    background-color: #EAEAEA;
}
/*Select entire sorted column ends*/

.mGrid .pgr
{
 background: #424242 url(Images/grd_pgr.png) repeat-x top;
 text-align: center; /*Make pager to be center*/
}
.mGrid .pgr table
{
 margin: 5px 0;
}
.mGrid .pgr td
{
 border-width: 0;
 color: #fff;
 font-weight: bold;
 line-height: 12px;
 padding: 0 6px;
 border-left: solid 1px #666;
}
.mGrid .pgr a
{
 color: #666;
 text-decoration: none;
}
.mGrid .pgr a:hover
{
 color: #000;
 text-decoration: none;
}



Download Images
Curtesy atashbahar

Monday, February 28, 2011

Grouping RadioButton inside gridveiw

        function uncheckOthers(id) {
            var elm = document.getElementsByTagName('input');
            for (var i = 0; i < elm.length; i++) {
                if (elm.item(i).id.substring(id.id.lastIndexOf('_')) == id.id.substring(id.id.lastIndexOf('_'))) {
                    if (elm.item(i).type == "radio" && elm.item(i) != id) elm.item(i).checked = false;
                }
            }
        }  
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //To make the RadioButton mutually exclusive
                string strScript = "uncheckOthers(" + ((RadioButton)e.Row.Cells[0].FindControl("rbSelect")).ClientID + ");";
                ((RadioButton)e.Row.Cells[0].FindControl("rbSelect")).Attributes.Add("onclick", strScript);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Selecting or DeSelecting multiple checkbox inside a gridview




function SelectAllOrDeselect(CheckBox, Type, Column, HCheckBox) {
    try {
        var TotalChkBx = parseInt('<%= grd_EmpSelection.Rows.Count %>');
        var TargetBaseControl = document.getElementById('<%= grd_EmpSelection.ClientID%>');
        var TargetChildControl = null;

        if (Column == "1") TargetChildControl = "chkTestSelect";
        else TargetChildControl = "chkTrainingSelect";

        var Inputs = TargetBaseControl.getElementsByTagName("input");
        var SelectCount = 0;
        //Checked/Unchecked all the checkBoxes in side the GridView.
        if (Type == "1") {
            for (var iCount = 0; iCount < Inputs.length; ++iCount) {
                if (Inputs[iCount].type == 'checkbox' && Inputs[iCount].id.indexOf(TargetChildControl, 0) >= 0) 
                    Inputs[iCount].checked = CheckBox.checked;
            }

            //Reset Counter
            SelectCount = CheckBox.checked ? TotalChkBx : 0;
        } else if (Type == "2") {
            //Reset Counter
            for (var iCount = 0; iCount < Inputs.length; ++iCount) {
                if (Inputs[iCount].type == 'checkbox' && Inputs[iCount].id.indexOf(TargetChildControl, 0) >= 0) 
                    if (Inputs[iCount].checked == true) SelectCount++;
            }

            //Modifiy Counter;        
            if (!CheckBox.checked && SelectCount > 0) SelectCount--;

            //Change state of the header CheckBox.
            if (SelectCount < TotalChkBx) HCheckBox.checked = false;
            else if (SelectCount == TotalChkBx) HCheckBox.checked = true;
        }
    } catch (err) {}
}
protected void grd_EmpSelection_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //e.Row.RowState == DataControlRowState.Edit not works on Alternating Rows 
        //if ((e.Row.RowState & DataControlRowState.Edit) > 0)
        if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
        {

            CheckBox chkTestSelectAll = (CheckBox)this.grd_EmpSelection.HeaderRow.FindControl("chkTestSelectAll");
            CheckBox chkTestSelect = (CheckBox)e.Row.Cells[1].FindControl("chkTestSelect");

            chkTestSelectAll.Attributes["onclick"] = string.Format("javascript:SelectAllOrDeselect(this,'1','1', {0});", chkTestSelectAll.ClientID);
            chkTestSelect.Attributes["onclick"] = string.Format("javascript:SelectAllOrDeselect(this,'2','1', {0});", chkTestSelectAll.ClientID);


            CheckBox chkTrainingSelectAll = (CheckBox)this.grd_EmpSelection.HeaderRow.FindControl("chkTrainingSelectAll");
            CheckBox chkTrainingSelect = (CheckBox)e.Row.Cells[1].FindControl("chkTrainingSelect");

            chkTrainingSelectAll.Attributes["onclick"] = string.Format("javascript:SelectAllOrDeselect(this,'1','2', {0});", chkTrainingSelectAll.ClientID);
            chkTrainingSelect.Attributes["onclick"] = string.Format("javascript:SelectAllOrDeselect(this,'2','2', {0});", chkTrainingSelectAll.ClientID);

        }
    }

The gridview checkbox will maintain the checked state during postback.

Reference
http://www.codeproject.com/KB/webforms/SelectingAllCheckBoxes.aspx

Thursday, December 2, 2010

Generate Insert Multiple Records Using One Insert Statement – Use of UNION ALL

Version I
DECLARE @TableName            VARCHAR(50)
DECLARE @ColNames AS          VARCHAR(8000)
DECLARE @InsColNames AS       VARCHAR(8000)
DECLARE @NewLineChar AS       VARCHAR(2)
DECLARE @HorizontalTabChar AS VARCHAR(1)
DECLARE @SQuoteFront AS       VARCHAR(15)
DECLARE @SQuoteBack AS        VARCHAR(15)
DECLARE @Comma AS             VARCHAR(150)

SET @SQuoteFront       = '''''''''+'
SET @SQuoteBack        = '+'''''''''
SET @Comma             = ''',''' + ', '
SET @TableName         = 'NetworkPath'
SET @NewLineChar       = CHAR(13) + CHAR(10)
SET @HorizontalTabChar = CHAR(9)

SELECT   @ColNames     = ( COALESCE (@ColNames + ( '''' + column_name + '''' + ', ' ), '') ),
         @InsColNames  = (
                  CASE
                           WHEN
                                    (
                                             data_type = 'bit'
                                    OR       data_type = 'bigint'
                                    OR       data_type = 'decimal'
                                    OR       data_type = 'float'
                                    OR       data_type = 'int'
                                    OR       data_type = 'money'
                                    OR       data_type = 'numeric'
                                    OR       data_type = 'tinyint'
                                    OR       data_type = 'image'
                                    )
                           THEN COALESCE (@InsColNames, '') + ( 'CAST( ' + column_name  + ' AS VARCHAR)' + ' + ' + '''' + ' AS ' + column_name + ''''   + ', ' + '''' + ',' + '''' + ',' )
                           ELSE COALESCE (@InsColNames, '') + ( @SQuoteFront + 'CAST( ' + column_name + ' AS VARCHAR('+ CAST(character_maximum_length AS VARCHAR)  +') )' + @SQuoteBack + ' + ' + '''' + ' AS ' + column_name + '''' + ', ' + @Comma )
                  END )
FROM     information_schema.columns
WHERE    table_name = @TableName
ORDER BY ordinal_position ASC

--Remove comma(,) at the end
SET @ColNames = LEFT(@ColNames, LEN(@ColNames) - 1)

--PRINT 'INSERT INTO ' + @TableName + ' ( ' + @ColNames + ' )'
--Generate Inserte statement for the given table
SELECT 'INSERT INTO ' + @TableName + ' ( ' + @ColNames + ' )' AS InsertStatement

--PRINT 'SELECT '+  @InsColNames + ' FROM ' + @TableName

--Remove ,',', at the end
SET @InsColNames = LEFT(@InsColNames, LEN(@InsColNames) - 5)
PRINT CHAR(13) + CHAR(10)

SELECT @InsColNames

/*
PRINT 'SELECT ' + '''SELECT ' + '''' + ' ,' + ' ' + @InsColNames +
''' UNION ALL' +
'''' + CHAR(13) + CHAR(10) + 'FROM ' + @TableName
*/

EXEC( 'SELECT ' + '''SELECT ' + '''' + ' ,' + ' ' + @InsColNames + ''' UNION ALL' + '''' + 'FROM ' + @TableName )

Version II
DECLARE @TableName            VARCHAR(50)
DECLARE @ColNames AS          VARCHAR(8000)
DECLARE @InsColNames AS       VARCHAR(8000)
DECLARE @NewLineChar AS       VARCHAR(2)
DECLARE @HorizontalTabChar AS VARCHAR(1)
DECLARE @SQuoteFront AS       VARCHAR(15)
DECLARE @SQuoteBack AS        VARCHAR(15)
DECLARE @Comma AS             VARCHAR(150)
SET @SQuoteFront       = '''''''''+'
SET @SQuoteBack        = '+'''''''''
SET @Comma             = ''',''' + ', '
SET @TableName         = 'NetworkPath'
SET @NewLineChar       = CHAR(13) + CHAR(10)
SET @HorizontalTabChar = CHAR(9)
SELECT   @ColNames     = ( COALESCE (@ColNames + ( '''' + column_name + '''' + ', ' ), '') ),
         @InsColNames  = (
         CASE
                  WHEN
                           (
                                    data_type = 'bit'
                           OR       data_type = 'bigint'
                           OR       data_type = 'decimal'
                           OR       data_type = 'float'
                           OR       data_type = 'int'
                           OR       data_type = 'money'
                           OR       data_type = 'numeric'
                           OR       data_type = 'tinyint'
                           OR       data_type = 'image'
                           )
                  THEN COALESCE (@InsColNames, '') + ( 'CAST( ' + column_name + ' AS VARCHAR)' + ' + ' + '''' + ' AS ' + column_name + '''' + ', ' + '''' + ',' + '''' + ',' )
                  ELSE COALESCE (@InsColNames, '') + ( @SQuoteFront + 'CAST( ' + column_name + ' AS VARCHAR('+ CAST(character_maximum_length AS VARCHAR) +') )' + @SQuoteBack + ' + ' + '''' + ' AS ' + column_name + '''' + ', ' + @Comma )
         END )
FROM     information_schema.columns
WHERE    table_name = @TableName
ORDER BY ordinal_position ASC
--Remove comma(,) at the end
SET @ColNames = LEFT(@ColNames, LEN(@ColNames) - 1)
--PRINT 'INSERT INTO ' + @TableName + ' ( ' + @ColNames + ' )'
--Generate Inserte statement for the given table
SELECT 'INSERT INTO ' + @TableName + ' ( ' + @ColNames + ' )' AS InsertStatement
--PRINT 'SELECT '+  @InsColNames + ' FROM ' + @TableName
--Remove ,',', at the end
SET @InsColNames = LEFT(@InsColNames, LEN(@InsColNames) - 5)
PRINT CHAR(13)                                          + CHAR(10)
SELECT @InsColNames
/*
PRINT 'SELECT ' + '''SELECT ' + '''' + ' ,' + ' ' + @InsColNames +
''' UNION ALL' +
'''' + CHAR(13) + CHAR(10) + 'FROM ' + @TableName
*/
EXEC( 'SELECT ' + '''SELECT ' + '''' + ' ,' + ' ' + @InsColNames + ''' UNION ALL' + '''' + 'FROM ' + @TableName )
Reference

Thursday, September 2, 2010

Collapsible Div

function ToggleCollapsible(ControlIdToShow, SaveStateField, ControlFireID) {
    var control = document.all[ControlIdToShow].style;
    var expandstate = document.all[SaveStateField];

    var ControlFireID = document.getElementById(ControlFireID);

    if (control.display == 'none') {
        control.display = '';
        expandstate.value = 'true';

        if (ControlIdToShow == "ToShow") {
            //showImageID.style.display = "none";
            //hideImageID.style.display = "block";
            //On button click change the image
            ControlFireID.src = "Collapsible/collapse.gif";
            ControlFireID.title = "Hide";
        }
    }
    else {
        control.display = 'none';
        expandstate.value = 'false';

        if (ControlIdToShow == "ToShow") {
            //showImageID.style.display = "block";
            //hideImageID.style.display = "none";
            //On button click change the image
            ControlFireID.src = "Collapsible/expand.gif";
            ControlFireID.title = "Show";
        }
    }

    return false;
}

<input type="hidden" name="CollapsiblePanelHidden" value="True" />
<input id="imgBtnShow" name="imgBtnShow" type="image" src="Collapsible/expand.gif"
onclick="return ToggleCollapsible (&#39;ToShow&#39;, &#39;CollapsiblePanelHidden&#39;, &#39;imgBtnShow&#39;)"
title="Show" style="display: block;" />
<div id="ToShow" style="display: none;">
<table id="ShowTable">
<tr>
<td>
<a id="ShowTableContent"
title="Click to expand/collapse" onclick="return ToggleCollapsible (&#39;PanelToShowOrHide&#39;, &#39;CollapsiblePanelHidden&#39;, &#39;imgBtnShow&#39;, &#39;imgBtnHide&#39;)"
href="#">Collapsible panel (click to expand).</a></td>
</tr>
<tr>
<td id="PanelToShowOrHide" style="width: 100%; display: none; color: Red;">
http://asp-tech.blogspot.com/
</td>
</tr>
</table>
</div>

Wednesday, September 1, 2010

Generate CSS DropDown Menu from DataBase

IF OBJECT_ID (N'dbo.MenuMain', N'U') IS NOT NULL
 DROP TABLE dbo.MenuMain;
GO

CREATE TABLE dbo.MenuMain(ID INT, [Name] VARCHAR(50),[Link] VARCHAR(50), [Title] VARCHAR(50), ParentID INT, [Order] INT)

INSERT INTO dbo.MenuMain

SELECT 1, 'CSS Drop Down Menus', NULL, NULL, 0, 1 UNION ALL
SELECT 2, 'Vertical CSS Pop-Out Menu', NULL, NULL, 0, 2 UNION ALL
SELECT 3, 'CSS Hover Navigation',     '#', 'SEO Consultants Directory', 2, 1 UNION ALL
SELECT 4, 'Horizontal Drop & Pop Menu', NULL, NULL, 0, 3 UNION ALL
SELECT 5, 'SEO Consultants Sample',     '#', 'SEO Consultants Vertical Example', 2, 2 UNION ALL
SELECT 6, 'Tanfa Demo example',         '#', 'Complete Example', 5, 1 UNION ALL
SELECT 7, 'Stage 1',                    '#', 'Vertical Menu - Page 1', 6, 1 UNION ALL
SELECT 8, 'Stage 2',                    '#', 'Vertical Menu - Page 2', 6, 2 UNION ALL
SELECT 9, 'Stage 3',                    '#', 'Vertical Menu - Page 3', 6, 3 UNION ALL
SELECT 10, 'Stage 4',                   '#', 'Vertical Menu - Page 4', 6, 4 UNION ALL
SELECT 11, 'Stage 5',                   '#', 'Vertical Menu - Page 5', 6, 5

SELECT   ID    ,
         [Name],
		 [Link],
		 [Title],
         CASE WHEN ParentID = 0
              THEN NULL
              ELSE ParentID
         END AS ParentID,
         [Order]
FROM     dbo.MenuMain
ORDER BY ParentID,
         [Order]
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text;

public partial class HorizontalCssMenu : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //http://ago.tanfa.co.uk/css/examples/menu/tutorial-h.html#hs7
        //http://www.alistapart.com/articles/horizdropdowns/

        if (!IsPostBack)
        {
            LoadMenu();
        }
    }

    private void LoadMenu()
    {
        DataTable dtMenu = LoadData();
        
        StringBuilder sbMenu = new StringBuilder();

        foreach (DataRow dr in dtMenu.Rows)
        {
            if (string.IsNullOrEmpty(Convert.ToString(dr["ParentID"]))
                || Convert.ToString(dr["ParentID"]) == "0")
            {
                if (sbMenu.Length != 0)
                    sbMenu.Append(Environment.NewLine);
                sbMenu.Append("
    " + Environment.NewLine); sbMenu.Append("
  • ");
    sbMenu.Append("

    " + Convert.ToString(dr["Name"]) + "

    " + Environment.NewLine);
    sbMenu.Append("
  • " + Environment.NewLine + "
"); } else { StringBuilder sbTemp = new StringBuilder(); if (Convert.ToInt32(dr["Order"]) == 1) sbTemp.Append(Environment.NewLine + "
    "); sbTemp.Append(Environment.NewLine + "
  • ");
    sbTemp.Append("" + Convert.ToString(dr["Name"]) + "");
    sbTemp.Append(Environment.NewLine + "
  • "); if (Convert.ToInt32(dr["Order"]) == 1) sbTemp.Append(Environment.NewLine + "
"); string id = "ID=\"" + Convert.ToString(dr["ParentID"]) + "\""; int length = sbMenu.ToString().IndexOf(id); if (length != -1) { string Previous = sbMenu.ToString().Substring(0, length); string Next = sbMenu.ToString().Substring(length); if (Convert.ToInt32(dr["Order"]) == 1) sbMenu.Insert((Previous.Length + Next.IndexOf(" ")), sbTemp); else sbMenu.Insert((Previous.Length + Next.IndexOf("")), sbTemp); } else sbMenu.Append(sbTemp); } } if (sbMenu.ToString().Length > 0) { menu.InnerHtml = sbMenu.ToString(); } } public DataTable LoadData() { DataSet dsUserMenu = null; try { //Connection string from Web.Config string sDBConnection = "SERVER=;DATABASE=;UID=;pwd="; string[] sTableName = { "Menu" }; string sQuery = @"SELECT ID , [Name], [Link], [Title], CASE WHEN ParentID = 0 THEN NULL ELSE ParentID END AS ParentID, [Order] FROM dbo.MenuMain ORDER BY ParentID, [Order]"; dsUserMenu = new DataSet(); DBHelper.FillDataset(sDBConnection, CommandType.Text, sQuery, dsUserMenu, sTableName); dsUserMenu.DataSetName = "Menus"; DataRelation objMenuRelation = new DataRelation("ParentChild", dsUserMenu.Tables["Menu"].Columns["ID"], dsUserMenu.Tables["Menu"].Columns["ParentID"], false); objMenuRelation.Nested = true; dsUserMenu.Relations.Add(objMenuRelation); return dsUserMenu.Tables[0]; } catch (Exception ex) { throw ex; } } }

Download .cs, .aspx, .css, .sql file form below
HorizontalCssMenu.zip


References
ago.tanfa.co.uk
Example
alistapart