Friday, July 8, 2011

Switch Theme Without Postback


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;

public partial class ChangeTheme : System.Web.UI.Page, ICallbackEventHandler
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        //If theme is null or not changed by user use Default theme
        if (String.IsNullOrEmpty(Convert.ToString(Session["Theme"])))
            Page.Theme = "Default";
        else
            Page.Theme = Convert.ToString(Session["Theme"]);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //JavaScript Callbacks
        ClientScriptManager scriptManager = Page.ClientScript;
        String cbReference = scriptManager.GetCallbackEventReference(this, "returnValue", "ReceiveServerData", "context");
        String callbackScript = "function CallServer(returnValue, context) {" + cbReference + "; }";
        scriptManager.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);

        TextBox1.Text = DateTime.Now.ToString();
    }

    #region ICallbackEventHandler Members
    //Return value from the server to the client
    string ICallbackEventHandler.GetCallbackResult()
    {
        return Convert.ToString(Session["Theme"]);
    }

    //Get the theme name from the javascript function
    public void RaiseCallbackEvent(string eventArgument)
    {
        Session["Theme"] = eventArgument.Trim();
    }

    #endregion
}

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




    Theme Switcher
    
    
    

    


    

The style set for the background body and the textbox.

You can see that, the time is not changed when we select the color.
This is done from the javascript.
To make apply the theme press the button Apply Theme.



Source Code

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