Wednesday, June 25, 2008

Display menu on rightClick of mouse on browser IE + Mozilla + Safari

Hi,
This document contains the technical details for component “right click”.

Requirement of component :-

Component: right-click
Rules:
Right-clicking should never do anything but display a menu.
Right-clicking should never offer an option that is not available through other methods.

Explanation :-

for this I created Javascript for show a Menu (Div) which containing the server controls . And a close button if user does not want to do any thing he can close Menu. This menu also show when user right click on image. A snip of script is follows In part A and in Part B dive containing a table with some link button which are able to perform action at server side.

This Script is working fine with Mozilla, Internet Explorer, And Safari

for Mozilla we have to call it “ oncontextmenumethod “ under body tag.
Like [body oncontextmenu="menuDiv(event);return false;"]

Part A

JavaScript :- .

[script language="JavaScript"]


//right mouse click Script

// Right-clicking should never do anything but display a menu.
// Right-clicking should never offer an option that is not available through other methods.


function menuDiv(e)
{



if (e == null) e = event;

var DivMenu = document.getElementById('DivMenu');

DivMenu.style.display = 'block';
// Region for Code Area for show div within page area
// note that width of div is 125px and height is 210

var top = 210;
var left = 870;

if( e.clientX ] left)
{
DivMenu.style.left = left+'px';


}
else
{
DivMenu.style.left = e.clientX+'px';



}

if(e.clientY [ top)
{

DivMenu.style.top = document.body.scrollTop;


}
else
{
DivMenu.style.top = (e.clientY-DivMenu.offsetHeight)+'px';

}


// End region of Code Area for show div within page area





return false;
}
//////////////////////////////////////////
// Browser Compatibility //
////////////////////////////////////////
function clickIE4(){
if (event.button==2){

menuDiv( event);
return false;
}
}

function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){

menuDiv( event);
return false;
}
}
}

if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}



document.oncontextmenu = new Function("menuDiv(event); return false") //ok working fine IE + Safari + Mozila








// Function for close div menu
function hideMenu()
{


document.getElementById('DivMenu').style.display='none';






return false;
}

[/script]


div

[div id="DivMenu" style="background-color:Bisque ; position: absolute; width: 125;
display: none; border: 2"]
//Add conrols here
[/div]
Part B
In this part I copy paste the complete javascript code form working page.

[title]Untitled Page[/title]
[script language="JavaScript"]


//right mouse click Script

// Right-clicking should never do anything but display a menu.
// Right-clicking should never offer an option that is not available through other methods.


function menuDiv(e)
{



if (e == null) e = event;

var DivMenu = document.getElementById('DivMenu');

DivMenu.style.display = 'block';
// Region for Code Area for show div within page area
// note that width of div is 125px and height is 210

var top = 210;
var left = 870;

if( e.clientX ] left)
{
DivMenu.style.left = left+'px';


}
else
{
DivMenu.style.left = e.clientX+'px';



}

if(e.clientY [ top)
{

DivMenu.style.top = document.body.scrollTop;


}
else
{
DivMenu.style.top = (e.clientY-DivMenu.offsetHeight)+'px';

}


// End region of Code Area for show div within page area





return false;
}
//////////////////////////////////////////
// Browser Compatibility //
////////////////////////////////////////
function clickIE4(){
if (event.button==2){

menuDiv( event);
return false;
}
}

function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){

menuDiv( event);
return false;
}
}
}

if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}



document.oncontextmenu = new Function("menuDiv(event); return false") //ok working fine IE + Safari + Mozila








// Function for close div menu
function hideMenu()
{


document.getElementById('DivMenu').style.display='none';






return false;
}

[/script]
[/head]
[body oncontextmenu="menuDiv(event);return false;"]
[form id="form1" runat="server"]
[div style="vertical-align:middle;"]
Right Click Anywhere
[/div]
[%-- Creating Menu. It will display on right click--%]
[div id="DivMenu" style="background-color:Bisque ; position: absolute; width: 125;
display: none; border: 2"]
[table]
[tr]
[td style="width: 100;"]
  Menu  [/td]
[td align="left"]
[asp:LinkButton ID="btnCancel" runat="server" Text="X" ForeColor="red" ToolTip="Close"
OnClientClick="return hideMenu(); " /][/td]
[/tr]
[tr]
[td colspan="2"]
[asp:LinkButton ID="btnFirst" runat="server" Text="First Selection" /][/td]
[/tr]
[%-----------------------------%]
[tr]
[td colspan="2"]
[asp:LinkButton ID="Button1" runat="server" Text="Second Selection" /][/td]
[/tr]
[%--------------------------------------%]
[tr]
[td colspan="2"]
[hr /]
[/td]
[/tr]
[tr]
[td colspan="2"]
[asp:LinkButton ID="Button2_" runat="server" Text="Third Selection" /][/td]
[/tr]
[%-----------------------------%]
[tr]
[td colspan="2"]
[asp:LinkButton ID="Button3" runat="server" Text="Fourth Selection" /][/td]
[/tr]
[%---------------------------------%]
[tr]
[td colspan="2"]
[hr /]
[/td]
[/tr]
[tr]
[td colspan="2"]
[asp:LinkButton ID="Button2" runat="server" Text="Fifth Selection" /][/td]
[/tr]
[%-----------------------------%]
[tr]
[td colspan="2"]
[asp:LinkButton ID="LinkButton1" runat="server" Text="Sixth Selection" /][/td]
[/tr]
[/table]
[/div]
[/form]
[/body]
[/html]

Thanks
Mahesh K. Sharma

Tuesday, June 24, 2008

How Create Custom Control Auto Suggest Box

Hi,
This document contains the technical details for component drop down list.
Requirement of component :-

Component: drop-down lists
Rules:
Typing the first letter of the word takes you immediately to the first word that

starts with that letter. Rapidly typing the first two letters takes you to the

first word that starts with those two letters.
Location of drop-down box arrows should be consistent relative to their fields

(e.g. always to the right of the field and never between the label and the

field), and arrows should have a consistent appearance throughout.

In part A we explained how to use the control and in Part B we explained how we

can created it


Before start code on application.
We have to add dll references . Second step is Add control toolbox.
Right click on tool Box -] choose items -] browse and locate custom

autoSuggestTextBox dll.
Drag control on page.


[%@ Register Assembly="autoSuggestTextBox" Namespace="autoSuggestTextBox"

TagPrefix="cc1" %]
[%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"

TagPrefix="ajaxToolkit" %]
This part contains the details how to use this control.

[form id="form1" runat="server"]
[asp:ScriptManager ID="ScriptManager1" runat="server"]
[Services]
[asp:ServiceReference Path="searchcusts.asmx" /]
[/Services]
[/asp:ScriptManager]
[div]
[asp:TextBox ID="txtFname" runat="server"][/asp:TextBox]
[br /]
[cc1:dropDownTextBox runat="server" TargetControlID="txtFname"

ServicePath="searchcusts.asmx"
ServiceMethod="GetCustList" MinimumPrefixLength="1"

EnableCaching="true"]
[/cc1:dropDownTextBox]
[/div]
[/form]

for this we must have create a webService which contained method for get data

from Table.

Sample code for webService is follows :-

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;

using System.Collections.Specialized;


//--------

using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;


/// [summary]
/// This is sample webService for using drop down text box custom control.
/// [/summary]
[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]


[System.Web.Script.Services.ScriptService]///Add with signature

"System.Web.Script.Services.ScriptService"
public class SearchCusts : System.Web.Services.WebService {



/// [summary]
/// Returns a list of Fname.
/// [/summary]
/// [param name="prefixText"]sarting letters of fname[/param]
/// [param name="count"]Number of total suggestion which retruns to drop

down list[/param]
/// [returns]A string array of suggestions[/returns]


[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] GetCustList(string prefixText, int count)
{
// string connString =

ConfigurationManager.ConnectionStrings["YourDB"].ToString();

string connString = @"Data Source=192.168.0.4\ver2005;Initial

Catalog=test_navdeep;User ID=navdeep;Password=navdeep";

string selectString = "SELECT DISTINCT TOP " + count.ToString() + " fname

from test1 WHERE fname LIKE '" + prefixText + "%'";

List[String] CustList = new List[string](count);
using (SqlConnection sqlConn = new SqlConnection(connString))
{
sqlConn.Open();

using (SqlCommand sqlCmd = new SqlCommand(selectString, sqlConn))
{
SqlDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read())
CustList.Add(reader["fname"].ToString());
}
}
return (CustList.ToArray());
}

}


http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx

Part B
For creating custom control we must add reference of ajaxcontroltoollkit.dll and

inherit our class with
AutoCompleteExtender class.Create its object and build solution. Thats create

our custom control. Simple code block for this as follows

using System;
using System.Collections.Generic;
using System.Text;
using AjaxControlToolkit;
using System.Web;

namespace autoSuggestTextBox
{
public class dropDownTextBox : AutoCompleteExtender
{
AutoCompleteExtender autoSuggestBox = new AutoCompleteExtender();

}
}

...
More property of custom control with description is follows :-



TargetControlID - The TextBox control where the user types content to be

automatically completed
ServiceMethod - The web service method to be called. The signature of this method

must match the following:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] GetCompletionList(string prefixText, int count) { ... }
Note that you can replace "GetCompletionList" with a name of your choice, but the

return type and parameter name and type must exactly match, including case.
ServicePath - The path to the web service that the extender will pull the

word\sentence completions from. If this is not provided, the service method

should be a page method.
ContextKey - User/page specific context provided to an optional overload of the

web method described by ServiceMethod/ServicePath. If the context key is used, it

should have the same signature with an additional parameter named contextKey of

type string:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] GetCompletionList(
string prefixText, int count, string contextKey) { ... }
Note that you can replace "GetCompletionList" with a name of your choice, but the

return type and parameter name and type must exactly match, including case.
UseContextKey - Whether or not the ContextKey property should be used. This will

be automatically enabled if the ContextKey property is ever set (on either the

client or the server). If the context key is used, it should have the same

signature with an additional parameter named contextKey of type string (as

described above).
MinimumPrefixLength - Minimum number of characters that must be entered before

getting suggestions from the web service.
CompletionInterval - Time in milliseconds when the timer will kick in to get

suggestions using the web service.
EnableCaching - Whether client side caching is enabled.
CompletionSetCount - Number of suggestions to be retrieved from the web service.
CompletionListCssClass - Css Class that will be used to style the completion list

flyout.
CompletionListItemCssClass - Css Class that will be used to style an item in the

AutoComplete list flyout.
CompletionListHighlightedItemCssClass - Css Class that will be used to style a

highlighted item in the AutoComplete list flyout.
DelimiterCharacters - Specifies one or more character(s) used to separate words.

The text in the AutoComplete textbox is tokenized using these characters and the

webservice completes the last token.
FirstRowSelected - Determines if the first option in the AutoComplete list will

be selected by default.
Animations - Generic animations for the AutoComplete extender. See the Using

Animations walkthrough and Animation Reference for more details.
OnShow - The OnShow animation will be played each time the AutoComplete

completion list is displayed. The completion list will be positioned correctly

but hidden. The animation can use [HideAction Visible="true" /] to display the

completion list along with any other visual effects.
OnHide - The OnHide animation will be played each time the AutoComplete

completion list is hidden.

Thanks and Regards
Mahesh K. Sharma

Custom calendar control with next and prev year button

Hi,
This document contains the Technical detail of custom control with possibility on enhancement in part A and how we can use use it is explained in part B.

functionality :-

Clicking on the calendar control brings the user to today’s date
Clicking on a single forward or backward arrow takes the user forward or backward one month
Clicking on a double forward or backward arrow takes the user forward or backward one year

Limitations :-

1) No designing property for page level programmer .
2)No return value from control.
3) Required more work on designing.

But easily we give property code is commented properly for remove this limitations.

Technical details of control. With commented coding.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Text.RegularExpressions;
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.Drawing;
namespace CalenderControl
{

public class CalenderControl : Control, INamingContainer
{
//-//////////////////////////////////////////////////////////////////////
// Control Deising
//-\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\


protected override void Render(HtmlTextWriter writer)
{
/// We can pass color type with property. That give page level programer to ability of desing the
/// control

style.BackColor = Color.LightYellow;



//-//////////////////////////////////////////////////////////////////////
// Previous Month / Year Button
//-\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

#region prevMonth/Year

//-//////////////////////////////////////////////////////////////////////
//-\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\


#region prevYear
writer.EnterStyle(style);
writer.RenderBeginTag(HtmlTextWriterTag.Tr);

/// Render Password Previous year calender
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.AddAttribute(HtmlTextWriterAttribute.For, btnPrevYear.ClientID);

writer.RenderEndTag(); // TD

// Render Button previous year
writer.RenderBeginTag(HtmlTextWriterTag.Td);
btnPrevYear.RenderControl(writer);
writer.RenderEndTag(); // TD

writer.RenderEndTag(); // TR

#endregion prevYear

//-//////////////////////////////////////////////////////////////////////
//-\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

#region Space
writer.RenderBeginTag(HtmlTextWriterTag.Tr);

///Render Label for spacing which width space we have to calculae dynamicly
/// for example if use short date value is 9/20/2007 and if dates value is changed
/// to 10/20/2007 means we have to calculate spacing for this date.
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.AddAttribute(HtmlTextWriterAttribute.For, lblForSpacingBetweenConrols2.ClientID);
writer.RenderEndTag();
writer.RenderEndTag();
writer.RenderBeginTag(HtmlTextWriterTag.Td);
///Render Label for spacing
lblForSpacingBetweenConrols2.RenderControl(writer);
writer.RenderEndTag();



#endregion Space

//-//////////////////////////////////////////////////////////////////////
//-\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

#region prevMonth
writer.EnterStyle(style);
writer.RenderBeginTag(HtmlTextWriterTag.Tr);

/// Render Previous year calender
writer.RenderBeginTag(HtmlTextWriterTag.Td);

writer.AddAttribute(HtmlTextWriterAttribute.For, btnPrevMonth.ClientID);
writer.RenderEndTag(); // Button Previous year calender
writer.RenderEndTag(); // TD
writer.RenderBeginTag(HtmlTextWriterTag.Td);
btnPrevMonth.RenderControl(writer); /// Render Previous year calender
writer.RenderEndTag(); // TD

// writer.RenderEndTag();

#endregion prevMonth

#endregion prevMonth/Year

//-//////////////////////////////////////////////////////////////////////
// Calenders Date
//-\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

#region lblHiglited date

writer.RenderBeginTag(HtmlTextWriterTag.Tr);

/// Render calander Date lable
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.AddAttribute(HtmlTextWriterAttribute.For, lblSelectedDate.ClientID);
writer.RenderEndTag(); // Label
writer.RenderEndTag(); // TD

/// Render calander Date lable
writer.RenderBeginTag(HtmlTextWriterTag.Td);
lblSelectedDate.RenderControl(writer);
writer.RenderEndTag(); // TD

#endregion lblHiglited date


//-//////////////////////////////////////////////////////////////////////
// Next Month / Year Button
//-\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

#region nextMonth/Year

#region nxtMonth

writer.EnterStyle(style);

writer.RenderBeginTag(HtmlTextWriterTag.Tr);

/// Render next month button
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.AddAttribute(HtmlTextWriterAttribute.For, lnkBtnNextMonth.ClientID);
writer.RenderEndTag(); // Button
writer.RenderEndTag(); // TD
/// Render next month button
writer.RenderBeginTag(HtmlTextWriterTag.Td);
lnkBtnNextMonth.RenderControl(writer);
writer.RenderEndTag(); // TD

#endregion nxtMonth

#region Space
writer.RenderBeginTag(HtmlTextWriterTag.Tr);

/// Render Label for spacing
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.AddAttribute(HtmlTextWriterAttribute.For, lblForSpacingBetweenConrols2.ClientID);
writer.RenderEndTag(); // Label
writer.RenderEndTag(); // TD

/// Render Label for spacing
writer.RenderBeginTag(HtmlTextWriterTag.Td);
lblForSpacingBetweenConrols2.RenderControl(writer);
writer.RenderEndTag(); // TD

#endregion Space

#region nxtYear
writer.RenderBeginTag(HtmlTextWriterTag.Tr);


/// Render next Year button
writer.RenderBeginTag(HtmlTextWriterTag.Td);
writer.AddAttribute(HtmlTextWriterAttribute.For, btnNextYear.ClientID);
writer.RenderEndTag(); // Button
writer.RenderEndTag(); // TD
/// Render next Year button
writer.RenderBeginTag(HtmlTextWriterTag.Td);
btnNextYear.RenderControl(writer);
writer.RenderEndTag(); // TD
#endregion nxtYear

#endregion nextMonth/Year




//-//////////////////////////////////////////////////////////////////////
// Calaender
//-\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

#region calender

/// We can pass color type with different property name like heder color. That give page level programer
/// ability of desing the header with diffenet type color.
///
/// Same we can give different styles to button, lable, calender, heder lable, forecolor, width etc
/// each n every control


style.BackColor = Color.LightSkyBlue;

writer.EnterStyle(style);

writer.RenderBeginTag(HtmlTextWriterTag.Tr);

/// Render calender
writer.RenderBeginTag(HtmlTextWriterTag.Td);

writer.AddAttribute(HtmlTextWriterAttribute.For, zimsCalendar.ClientID);

writer.RenderEndTag(); // Calender
writer.RenderEndTag(); // TD

/// Render calender
writer.RenderBeginTag(HtmlTextWriterTag.Td);
zimsCalendar.RenderControl(writer);
writer.RenderEndTag(); // TD

#endregion calender

}

//-//////////////////////////////////////////////////////////////////////
// Property and Varialbes
//-\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

#region property and variables


bool handled = false;



public event EventHandler NextMonth;
public event EventHandler NextYear;

public event EventHandler PrevMonth;
public event EventHandler PrevYear;

Button btnNextMonth = new Button();
LinkButton lnkBtnNextMonth = new LinkButton();
LinkButton btnNextYear = new LinkButton();
Calendar zimsCalendar = new Calendar();
LinkButton btnPrevMonth = new LinkButton();
LinkButton btnPrevYear = new LinkButton();
Label lblSelectedDate = new Label();

Label lblForSpacingBetweenConrols = new Label();
Label lblForSpacingBetweenConrols2 = new Label();

Style style = new Style();


#endregion property and variables

//-//////////////////////////////////////////////////////////////////////
// Create and Add controls
//-\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

#region Create design view of control

protected override void CreateChildControls()///Called by the ASP.NET page framework to notify server controls
/// that use composition-based implementation to create any child
/// controls they contain in preparation for posting back or
/// rendering
{
#region Add controls for
//---------------------------------------

// Add link button for next month
lnkBtnNextMonth.Text = "]";
lnkBtnNextMonth.CommandName = "NextMonth";
lnkBtnNextMonth.ToolTip = "Next Month";
// lnkBtnNextMonth.BackColor = Color.Maroon;
///We can assigned its color by property which able programmer.
///here we commented this code line.
Controls.Add(lnkBtnNextMonth);



//----------------------------------------
lblForSpacingBetweenConrols2.Text = " ";
lblForSpacingBetweenConrols2.Width = 50;
Controls.Add(lblForSpacingBetweenConrols2);
//---------------------------------------

btnNextYear.Text = "]]";
btnNextYear.ToolTip = "Next Year";
// btnNextYear.BackColor = Color.Maroon;
///We can assigned its color by property which able programmer.
///here we commented this code line.
btnNextYear.CommandName = "NextYear";
Controls.Add(btnNextYear);
//----------------------------------------


lblSelectedDate.Text = "  " + zimsCalendar.TodaysDate.ToShortDateString() + "  ";

Controls.Add(lblSelectedDate);



/*//////////////////////////////////////////////*/



zimsCalendar.ID = "zimsCalendar";
zimsCalendar.ShowTitle = false;
zimsCalendar.TodaysDate = DateTime.Now;
zimsCalendar.TodayDayStyle.BackColor = Color.LightSlateGray;

///We can assigned its color by property which able programmer.

zimsCalendar.ShowNextPrevMonth = false;
Controls.Add(zimsCalendar);








/*\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/

//---------------------------------------

btnPrevMonth.Text = "[";
// btnPrevMonth.BackColor = Color.Maroon;
///We can assigned its color by property which able programmer.
///here we commented this code line.
btnPrevMonth.ToolTip = " Previous Month";
btnPrevMonth.CommandName = "PrevMonth";
Controls.Add(btnPrevMonth);

//----------------------------------------


lblForSpacingBetweenConrols2.Text = " ";
lblForSpacingBetweenConrols2.Width = 50;
lblForSpacingBetweenConrols2.BorderColor = Color.Magenta;
// lblForSpacingBetweenConrols2.BackColor = Color.Maroon;


Controls.Add(lblForSpacingBetweenConrols);

//---------------------------------------

btnPrevYear.Text = "[[";
btnPrevYear.ToolTip = "Previous Year";
// btnPrevYear.BackColor = Color.Maroon;
btnPrevYear.CommandName = "PrevYear";
Controls.Add(btnPrevYear);

//----------------------------------------


#endregion Create design view of control
}

#endregion Create design view of control


//-//////////////////////////////////////////////////////////////////////
// Handling Events
//-\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

#region override BubbleEvent
protected override bool OnBubbleEvent(object Source, EventArgs Sender)///These methods are OnBubbleEvent and
///RaiseBubbleEvent. We will be using the OnBubbleEvent for our event handling.
///So here is the code for the method that we override for usage within our own class.
{
#region virtual bubleEvent


//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

/// For code optimizing we must have to use case statement

//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

if (Sender is CommandEventArgs)
{

CommandEventArgs ce = (CommandEventArgs)Sender;

if (ce.CommandName == "NextMonth") /// if we contain two button on composite then we determine to fire it
/// delepending on its command name on button
{

onNextMonth(ce);
handled = true;
}
//-----------------------------------------------------------------

if (ce.CommandName == "NextYear") /// if we contain two button on composite then we determine to fire it
/// delepending on its command name on button
{

onNextYear(ce);
handled = true;
}
//-------------------------------------------------------------------

if (ce.CommandName == "PrevMonth") /// if we contain two button on composite then we determine to fire it
/// delepending on its command name on button
{

onPrevMonth(ce);
handled = true;
}
//--------------------------------------------------------------------

if (ce.CommandName == "PrevYear") /// if we contain two button on composite then we determine to fire it
/// delepending on its command name on button
{

onPrevMonth(ce);
handled = true;
}


}

return handled;

#endregion virtual bubleEvent

}

#endregion override BubbleEvent

//-//////////////////////////////////////////////////////////////////////
// Create Functions for event
//-\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

#region function for bubble Event

protected virtual void onNextMonth(EventArgs Sender)
{
#region onNextMonth
if (NextMonth != null)
{

zimsCalendar.TodaysDate = zimsCalendar.TodaysDate.AddMonths(1);

lblSelectedDate.Text = zimsCalendarTodaysDate();
// lblSelectedDate.BackColor = Color.Maroon;

///We can return the selected To Days date by property


}
#endregion onNextYear
}




protected virtual void onNextYear(EventArgs Sender)
{
#region onNextYear
if (NextYear != null)
{


zimsCalendar.TodaysDate = zimsCalendar.TodaysDate.AddYears(1);
lblSelectedDate.Text = zimsCalendarTodaysDate();
// lblSelectedDate.BackColor = Color.Maroon;

///We can return the selected To Days date by property




}
#endregion onNextYear
}




protected virtual void onPrevMonth(EventArgs Sender)
{
#region onPrevMonth
if (PrevMonth != null)
{


zimsCalendar.TodaysDate = zimsCalendar.TodaysDate.AddMonths(-1);

lblSelectedDate.Text = zimsCalendarTodaysDate(); /
// lblSelectedDate.BackColor = Color.Maroon;

///We can return the selected To Days date by property


}
#endregion onPrevMonth
}



protected virtual void onPrevYear(EventArgs Sender)
{
#region onPrevYear
if (PrevYear != null)
{


zimsCalendar.TodaysDate = zimsCalendar.TodaysDate.AddYears(-1);


lblSelectedDate.Text = zimsCalendarTodaysDate();

///We can return the selected To Days date by property



}
#endregion onPrevYear
}

#endregion function for bubble Event


//-//////////////////////////////////////////////////////////////////////
// Set Date on lable
//-\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

#region Set Date on Lable
/// [summary]
/// Thsi function set Todays date of prev/next month/year.
/// [/summary]
/// [returns] string [/returns]
private string zimsCalendarTodaysDate()
{

return ( "  " + zimsCalendar.TodaysDate.ToShortDateString() + "  ");
}

#endregion Set Date on Lable

}
}

Part B

Before start code on application.
We have to add dll references . Second step is Add control toolbox.
Right click on tool Box -] choose items -] browse and locate custom calender dll.
Drag control on page.

This part contains the details how to use this control.

[cc1:CalenderControl ID="CalenderControl1" OnNextYear="NY" OnNextMonth ="NM" OnPrevMonth ="PM" OnPrevYear = "PY" runat="server"]
[/cc1:CalenderControl]

protected void NY(object sender, EventArgs e)
{
// Here we can get values from cliked event
}



protected void NM(object sender, EventArgs e)
{
// Here we can get values from cliked event

}

protected void PM(object sender, EventArgs e)
{
// Here we can get values from cliked event

}



protected void PY(object sender, EventArgs e)
{
// Here we can get values from cliked event

}
Thanks.

Mahesh K. Sharma

Tuesday, June 17, 2008

Custom control for resizing, tabing,soritng and how to use

Hi,

This document contain the details of how to create custom control of grid view.
This Custom control contain the functionality for page level programmer

a) Sorting by clicking on header of grid view

b) Navigate to other page with Query String of cell text.

c)Show message “There are too many records to sort – please add more criteria” or something like if grid contains more recodes Max Record property.

d) Resizing columns of grid by dragging vertical line on header tab.

e)Tabbing moves from field to field, first left to right then down.
Limitations:-
a)Many portion of dll is currently hard coded like tabbing index, navigation link but we can easily assigns it with property as we already take max records property.

b) No designer codes for control.

c)No visible description for page level programmer about property of controls.


Paddings work:-

Here we should completable our grid to expend its width on double click on page.

How to use:-

A simple use of control is give in B part of this document . Still we have to use Ajax for dragging the headers. Its worked fine and complete Javascript with relevant and technical comments. Has been written .

Part A

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

namespace searchControl
{

public class SortedGridContrl : Control, INamingContainer
{



/// The Control class is the base class for all ASP.NET server controls.

///INamingContainer is a marker interface without method. When a control inherits with INamingContainer,
///the ASP.NET page framework creates a new naming scope under that control,this ensur us that the child
///controls have unique names.

///About our approch of create sorted gridView Control :-
/// I add a property MaxReocrd which we can set for a message display for max records on
/// If the grid is too large (e.g. if it has so many records that sorting it will kill the server),
/// user gets a message when they try to sort that says “There are too many records to sort –
/// please add more criteria” or something like that.
///
/// This is Example custom control with possibility of enhancement. connection string as property
/// suitable name if we want to fill dataset every time from dataset.if we have to use itemtemplate etc.

/// How to use :-
/// Add reff of dll and choose it as a tool. and drag drop on page from tool box.
///
///
/// on CS page :-
/// page load :- SortedGridContrl1.DataSetSource = dst;
/// and nothing code for soting, only click the header.
/// On:- aspx page
/// ]cc1:SortedGridContrl ID="SortedGridContrl1" runat="server" MaxReocrd=25 ]
///]/cc1:SortedGridContrl]

#region property and variables

private static Int16 cellIndex =99; /// Used for tabing in GridCell we set here heigher tab index for
/// GridView cell which will not distrub the tabindex of conrols page
/// In future we will suppy it with property.
private int RowIdex; /// Used for tabing in GridCell

private DataSet _dstforSorting = new DataSet();
private DataView _dv = new DataView();
private DataTable _dt = new DataTable();
private int? _MaxReocrd = null;
private DataSet _DataSetSource = new DataSet();

public int MaxReocrd
{

set { _MaxReocrd = value; }
}


/// ]summary]
/// Using this viewstate we save a DATABASE round for fill dataset.
/// ]/summary]
public DataSet DataSetSource
{

set
{
ViewState["ViewStateDst"] = value;
_dstforSorting = (DataSet)ViewState["ViewStateDst"];
}
}

private Label lblIfRowMoreThanLimit = new Label();

private GridView GV = new GridView();



#endregion property and variables






#region Create design view of control
protected override void CreateChildControls()///Called by the ASP.NET page framework to notify server controls
/// that use composition-based implementation to create any child
/// controls they contain in preparation for posting back or
/// rendering
{





#region gridView
GV.ID = "ZimsPoc";

GV.EnableViewState = true;
GV.AllowSorting = true;
GV.ShowHeader = true;
GV.AutoGenerateColumns = true;

GV.AllowSorting = true;




GV.Sorting += new GridViewSortEventHandler(this.GV_Sorting);
// GV.RowDataBound += new GridViewRowEventHandler(this.GV_RowDataBound);
GV.RowDataBound += new GridViewRowEventHandler(this.GV_RowDataBound);





/// The Sorting event is raised when the hyperlink to sort a column is clicked, but before the GridView
/// control handles the sort operation. This allows you to provide an event-handling method that performs
/// a custom routine



GV.DataSource = (DataSet)ViewState["ViewStateDst"];
GV.DataBind();

Controls.Add(GV);

#endregion gridView


}
#endregion Create design view of control






/// ]summary]
/// handling GridViewSortEventHandler . instance of the delegate to the event. And pass
/// GridViewSortEventArgs as agrument in sortedDataView function where sorting acctually taking place.
/// ]/summary]
/// ]param name="sender"]GridViewGV]/param]
/// ]param name="e"] GridViewSortEventHandler]/param]
protected virtual void GV_Sorting(Object sender, GridViewSortEventArgs e)
{
GV.DataSource = sortedDataView(e.SortExpression);

GV.DataBind();

}


/// ]summary]
/// handling GridViewRowDataBoundHandler.instance of the delegate to the event.
/// ]/summary]
/// ]param name="sender"]Object sender]/param]
/// ]param name="e"]GridViewRowEventArgs]/param]
void GV_RowDataBound(Object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.DataRow)
{

///Looping for Add Tabing functionality i GridView and link is provided for
///navigate to new page. which will geting by page level user as a property
///of custom control.
#region Tabing

for (RowIdex = 0; RowIdex ] e.Row.Cells.Count; RowIdex = RowIdex + 1)
{
if (RowIdex ] 0)
{
e.Row.Cells[RowIdex].Text = "]a href='http://www.google.com?id=" + e.Row.Cells[RowIdex].Text + "' target=blank]" + e.Row.Cells[RowIdex].Text + "]/a]";
}

e.Row.Cells[RowIdex].TabIndex = cellIndex;
cellIndex += 1;
}
#endregion Tabing

}
}


/// ]summary]
/// Performing sorting of dataSet.
/// ]/summary]
/// ]param name="sortExp"]string sortExpression]/param]
/// ]returns]DataView]/returns]
private DataView sortedDataView(string sortExp)
{
_dstforSorting = (DataSet)ViewState["ViewStateDst"];
_dt = _dstforSorting.Tables[0];
_dv = _dstforSorting.Tables[0].DefaultView;
_dv.Sort = sortExp;

return _dv;
}
/// ]summary]
/// If the grid is too large
/// (e.g. if it has so many records that sorting it will kill the server),
/// user gets a message when they try to sort that says “There are too many records to sort
/// – please add more criteria” or something like that.
/// ]/summary]
private void MessageforMaxRecords()
{
if (_MaxReocrd != null)
{

if (_dstforSorting.Tables[0].Rows.Count ] _MaxReocrd)
{

lblIfRowMoreThanLimit.Text = "There are too many records to sort ]br/] – please add more criteria.";
Controls.Add(lblIfRowMoreThanLimit);
Controls.Add(new LiteralControl("]br/]"));


}
}

}

}
}




Part B
Html Part :

]%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %]

]%@ Register Assembly="SortedGridComponenet" Namespace="searchControl" TagPrefix="cc1" %]

]!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"]
]html xmlns="http://www.w3.org/1999/xhtml"]
]head id="head" runat="server"]

]title]Untitled]/title]

]!-- set css for table --]

]style type="text/css"]
table { table-layout: fixed; width:700; }
td { word-wrap: break-word; text-overflow:ellipsis; overflow:hidden; white-space:nowrap; }
]/style]



]/head]
]body]
]form id="form" runat="server"]
]asp:ScriptManager runat="server" /]


]div style="width: 95%;"]
]p]
]b] how to use ]/b]]br /]]br /]

1) Drags Lines between headers columns
]br /]]br /]
Steps to implement.
]br /]]br /]
a) Add reff of sortedcustom control gridview dll.
]br /]
b) Add [ asp:ScriptManager ID="ScriptManager1" runat="server" /]
]br /]]br /]
c) put our control between updatePanel ]br /]
[asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"]
[ContentTemplate]
[cc1:SortedGridContrl ID="SortedGridContrl2" runat="server"]
[/cc1:SortedGridContrl]

[/ContentTemplate]
[/asp:UpdatePanel]
]br /]]br /]

d) Add javaScript which written follows
]br /]]br /]

e)Don't forget add above style after title
[style type="text/css"]
table { table-layout: fixed; width:700px; }
td { word-wrap: break-word; text-overflow:ellipsis; overflow:hidden; white-space:nowrap; }
[/style]
]br /]
f)add on little code in sortedgridview custom conttrol GV.ID="zimspoc" or alter little bit
javaScript


]br /]]br /]





]/p]
]br /]
]asp:UpdatePanel runat="server" UpdateMode="Conditional"]
]ContentTemplate]


]cc1:SortedGridContrl ID="SortedGridContrl1" runat="server"]
]/cc1:SortedGridContrl]

]/ContentTemplate]
]/asp:UpdatePanel]
]/div]


]script type="text/javascript"]


// true when a header is currently being resized
var _isResizing;
// a reference to the header column that is being resized
var _element;
// an array of all of the tables header cells
var _ths;

function pageLoad(args){

// get all of the th elements from the gridview

if($get('ZimsPoc') == null) // it is ID + _ + Zimspoc it is true after post back
{

_ths = $get('SortedGridContrl1_ZimsPoc').getElementsByTagName('th');


}
if($get('ZimsPoc') != null) // it is true first time on load
{
_ths = $get('ZimsPoc').getElementsByTagName('th');
}


// if the grid has at least one th element
if(_ths.length ] 1){


for(i = 0; i ] _ths.length; i++){
// determine the widths
_ths[i].style.width = Sys.UI.DomElement.getBounds(_ths[i]).width + 'px';

// attach the mousemove and mousedown events
if(i ] _ths.length - 1){
$addHandler(_ths[i], 'mousemove', _onMouseMove);
$addHandler(_ths[i], 'mousedown', _onMouseDown);
}
}

// add a global mouseup handler
$addHandler(document, 'mouseup', _onMouseUp);
// add a global selectstart handler
$addHandler(document, 'selectstart', _onSelectStart);
}
}

function _onMouseMove(args){
if(_isResizing){



// determine the new width of the header
var bounds = Sys.UI.DomElement.getBounds(_element);
var width = args.clientX - bounds.x;

// we set the minimum width to 1 px, so make
// sure it is at least this before bothering to
// calculate the new width
if(width ] 1){

// get the next th element so we can adjust its size as well
var nextColumn = _element.nextSibling;
var nextColumnWidth;
if(width ] _toNumber(_element.style.width)){
// make the next column bigger
nextColumnWidth = _toNumber(nextColumn.style.width) + _toNumber(_element.style.width) - width;
}
else if(width ] _toNumber(_element.style.width)){
// make the next column smaller
nextColumnWidth = _toNumber(nextColumn.style.width) - (width - _toNumber(_element.style.width));
}

// we also don't want to shrink this width to less than one pixel,
// so make sure of this before resizing ...
if(nextColumnWidth ] 1){
_element.style.width = width + 'px';
nextColumn.style.width = nextColumnWidth + 'px';
}
}
}
else{
// get the bounds of the element. If the mouse cursor is within
// 2px of the border, display the e-cursor -] cursor:e-resize
var bounds = Sys.UI.DomElement.getBounds(args.target);
if(Math.abs((bounds.x + bounds.width) - (args.clientX)) ]= 2) {
args.target.style.cursor = 'e-resize';
}
else{
args.target.style.cursor = '';
}
}
}

function _onMouseDown(args){
// if the user clicks the mouse button while
// the cursor is in the resize position, it means
// they want to start resizing. Set _isResizing to true
// and grab the th element that is being resized
if(args.target.style.cursor == 'e-resize') {
_isResizing = true;
_element = args.target;
}
}

function _onMouseUp(args){
// the user let go of the mouse - so
// they are done resizing the header. Reset
// everything back
if(_isResizing){

// set back to default values
_isResizing = false;
_element = null;

// make sure the cursor is set back to default
for(i = 0; i ] _ths.length; i++){
_ths[i].style.cursor = '';
}
}
}

function _onSelectStart(args){
// Don't allow selection during drag
if(_isResizing){
args.preventDefault();
return false;
}
}

function _toNumber(m) {
// helper function to peel the px off of the widths
return new Number(m.replace('px', ''));
}

]/script]


]/form]
]/body]
]/html]



Code Behind Part:-

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
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 _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sq0lcon = new SqlConnection(@"Data Source=192.168.0.4\ver2005;Initial Catalog=test_navdeep;User ID=navdeep;Password=navdeep");
DataSet dst = new DataSet();
SqlDataAdapter dadAuthors;
SqlCommand sqlcmd = new SqlCommand("Select * from Test1", sq0lcon);
dadAuthors = new SqlDataAdapter(sqlcmd);

dadAuthors.Fill(dst, "dst");



SortedGridContrl1.DataSetSource = dst;

}

}

how to kill cache of page for new loding of page

Write this code on pageLoad or PostBack Event.

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();

Cache.Remove("CacheID");

Wednesday, June 11, 2008

session expire redirect login page redirect to expire paage like

session time out session expire redirect login page redirect to expire paage like

yahoo


set session time out for 20 minutes

[system.web]

[sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424"

sqlConnectionString="data source=74.54.60.18\ver2005 ;Trusted_Connection=yes"

cookieless="false" timeout="20"/]

now code for if session is expire then re direct on your seesion is
expire page



protected void Page_PreRender(object sender, EventArgs e)
{
HttpContext.Current.Response.AppendHeader("Refresh",

Convert.ToString(((HttpContext.Current.Session.Timeout * 60) - 5)) + "; Url=

Default.aspx");

}

Tuesday, June 10, 2008

Resizing GridView Header

Hi,

In previius post I created a hybrid GridView and now we add at page level new attribute to it for Resizing its header by draging it. we need to ajax enabled site.
ohh Plz add little code in sortedGridcomponent GV.Id="zimspoc" or alter javascript on page.






[%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %]

[%@ Register Assembly="SortedGridComponenet" Namespace="searchControl" TagPrefix="cc1" %]


[!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"]
[html xmlns="http://www.w3.org/1999/xhtml"]
[head id="head" runat="server"]

[title]Untitled[/title]

[!-- set css for table --]

[style type="text/css"]
table { table-layout: fixed; width:700px; }
td { word-wrap: break-word; text-overflow:ellipsis; overflow:hidden; white-space:nowrap; }
[/style]



[/head]
[body]
[form id="form" runat="server"]
[asp:ScriptManager runat="server" /]


[div style="width: 95%;"]
[p]
[b] how to use [/b][br /][br /]

1) Drags Lines between headers columns
[br /][br /]
Steps to implement.
[br /][br /]
a) Add reff of sortedcustom control gridview dll.
[br /]
b) Add [ asp:ScriptManager ID="ScriptManager1" runat="server" /]
[br /][br /]
c) put our control between updatePanel [br /]
[asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"]
[ContentTemplate]
[cc1:SortedGridContrl ID="SortedGridContrl2" runat="server"]
[/cc1:SortedGridContrl]

[/ContentTemplate]
[/asp:UpdatePanel]
[br /][br /]

d) Add javaScript which written follows
[br /][br /]

e)Don't forget add above style after title
[style type="text/css"]
table { table-layout: fixed; width:700px; }
td { word-wrap: break-word; text-overflow:ellipsis; overflow:hidden; white-space:nowrap; }
[/style]
[br /][br /]





[/p]
[br /]
[asp:UpdatePanel runat="server" UpdateMode="Conditional"]
[ContentTemplate]


[cc1:SortedGridContrl ID="SortedGridContrl1" runat="server"]
[/cc1:SortedGridContrl]

[/ContentTemplate]
[/asp:UpdatePanel]
[/div]


[script type="text/javascript"]

// true when a header is currently being resized
var _isResizing;
// a reference to the header column that is being resized
var _element;
// an array of all of the tables header cells
var _ths;

function pageLoad(args){

// get all of the th elements from the gridview

if($get('ZimsPoc') == null) // it is ID + _ + Zimspoc it is true after post back
{

_ths = $get('SortedGridContrl1_ZimsPoc').getElementsByTagName('th');


}
if($get('ZimsPoc') != null) // it is true first time on load
{
_ths = $get('ZimsPoc').getElementsByTagName('th');
}


// if the grid has at least one th element
if(_ths.length ] 1){

for(i = 0; i [ _ths.length; i++){
// determine the widths
_ths[i].style.width = Sys.UI.DomElement.getBounds(_ths[i]).width + 'px';

// attach the mousemove and mousedown events
if(i [ _ths.length - 1){
$addHandler(_ths[i], 'mousemove', _onMouseMove);
$addHandler(_ths[i], 'mousedown', _onMouseDown);
}
}

// add a global mouseup handler
$addHandler(document, 'mouseup', _onMouseUp);
// add a global selectstart handler
$addHandler(document, 'selectstart', _onSelectStart);
}
}

function _onMouseMove(args){
if(_isResizing){

// determine the new width of the header
var bounds = Sys.UI.DomElement.getBounds(_element);
var width = args.clientX - bounds.x;

// we set the minimum width to 1 px, so make
// sure it is at least this before bothering to
// calculate the new width
if(width ] 1){

// get the next th element so we can adjust its size as well
var nextColumn = _element.nextSibling;
var nextColumnWidth;
if(width [ _toNumber(_element.style.width)){
// make the next column bigger
nextColumnWidth = _toNumber(nextColumn.style.width) + _toNumber(_element.style.width) - width;
}
else if(width ] _toNumber(_element.style.width)){
// make the next column smaller
nextColumnWidth = _toNumber(nextColumn.style.width) - (width - _toNumber(_element.style.width));
}

// we also don't want to shrink this width to less than one pixel,
// so make sure of this before resizing ...
if(nextColumnWidth ] 1){
_element.style.width = width + 'px';
nextColumn.style.width = nextColumnWidth + 'px';
}
}
}
else{
// get the bounds of the element. If the mouse cursor is within
// 2px of the border, display the e-cursor -] cursor:e-resize
var bounds = Sys.UI.DomElement.getBounds(args.target);
if(Math.abs((bounds.x + bounds.width) - (args.clientX)) [= 2) {
args.target.style.cursor = 'e-resize';
}
else{
args.target.style.cursor = '';
}
}
}

function _onMouseDown(args){
// if the user clicks the mouse button while
// the cursor is in the resize position, it means
// they want to start resizing. Set _isResizing to true
// and grab the th element that is being resized
if(args.target.style.cursor == 'e-resize') {
_isResizing = true;
_element = args.target;
}
}

function _onMouseUp(args){
// the user let go of the mouse - so
// they are done resizing the header. Reset
// everything back
if(_isResizing){

// set back to default values
_isResizing = false;
_element = null;

// make sure the cursor is set back to default
for(i = 0; i [ _ths.length; i++){
_ths[i].style.cursor = '';
}
}
}

function _onSelectStart(args){
// Don't allow selection during drag
if(_isResizing){
args.preventDefault();
return false;
}
}

function _toNumber(m) {
// helper function to peel the px off of the widths
return new Number(m.replace('px', ''));
}

[/script]


[/form]
[/body]
[/html]

Monday, June 9, 2008

Create Custom Sortable GridView

Hi, all this is a server custom control for a gridview. which allow sorting on click on its header. and Page Level Programmer not need to put a line for sorting :)
using System;
using System.Web;
using System.Web.UI;
using System.Drawing;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace searchControl
{

public class SortedGridContrl : Control, INamingContainer
{



/// The Control class is the base class for all ASP.NET server controls.

///INamingContainer is a marker interface without method. When a control inherits with INamingContainer,
///the ASP.NET page framework creates a new naming scope under that control,this ensur us that the child
///controls have unique names.

///About our approch of create sorted gridView Control :-
/// I add a property MaxReocrd which we can set for a message display for max records on
/// If the grid is too large (e.g. if it has so many records that sorting it will kill the server),
/// user gets a message when they try to sort that says “There are too many records to sort –
/// please add more criteria” or something like that.
///
/// This is Example custom control with possibility of enhancement. connection string as property
/// suitable name if we want to fill dataset every time from dataset.if we have to use itemtemplate etc.

/// How to use :-
/// Add reff of dll and choose it as a tool. and drag drop on page from tool box.
///
///
/// on CS page :-
/// page load :- SortedGridContrl1.DataSetSource = dst;
/// and nothing code for soting, only click the header.
/// On:- aspx page
/// [cc1:SortedGridContrl ID="SortedGridContrl1" runat="server" MaxReocrd=25 ]
///[/cc1:SortedGridContrl]

#region property and variables


private DataSet _dstforSorting = new DataSet();
private DataView _dv = new DataView();
private DataTable _dt = new DataTable();
private int? _MaxReocrd = null;
private DataSet _DataSetSource = new DataSet();

public int MaxReocrd
{

set { _MaxReocrd = value; }
}


///
/// Using this viewstate we save a DATABASE round for fill dataset.
///

public DataSet DataSetSource
{

set
{
ViewState["ViewStateDst"] = value;
_dstforSorting = (DataSet)ViewState["ViewStateDst"];
}
}

private Label lblIfRowMoreThanLimit = new Label();

private GridView GV = new GridView();



#endregion property and variables






#region Create design view of control
protected override void CreateChildControls()///Called by the ASP.NET page framework to notify server controls
/// that use composition-based implementation to create any child
/// controls they contain in preparation for posting back or
/// rendering
{




if (!Controls.Contains(GV))
{
#region gridView

GV.EnableViewState = true;
GV.AllowSorting = true;
GV.ShowHeader = true;
GV.AutoGenerateColumns = true;
GV.AllowSorting = true;




GV.Sorting += new GridViewSortEventHandler(this.GV_Sorting);
/// The Sorting event is raised when the hyperlink to sort a column is clicked, but before the GridView
/// control handles the sort operation. This allows you to provide an event-handling method that performs
/// a custom routine



GV.DataSource = (DataSet)ViewState["ViewStateDst"];
GV.DataBind();

Controls.Add(GV);

#endregion gridView
}

}
#endregion Create design view of control






///
/// handling GridViewSortEventHandler . instance of the delegate to the event. And pass
/// GridViewSortEventArgs as agrument in sortedDataView function where sorting acctually taking place.
///

/// GridViewGV
/// GridViewSortEventHandler
protected virtual void GV_Sorting(Object sender, GridViewSortEventArgs e)
{
GV.DataSource = sortedDataView(e.SortExpression);

GV.DataBind();

}
///
/// Performing sorting of dataSet.
///

/// string sortExpression
/// DataView
private DataView sortedDataView(string sortExp)
{
_dstforSorting = (DataSet)ViewState["ViewStateDst"];
_dt = _dstforSorting.Tables[0];
_dv = _dstforSorting.Tables[0].DefaultView;
_dv.Sort = sortExp;

return _dv;
}
///
/// If the grid is too large
/// (e.g. if it has so many records that sorting it will kill the server),
/// user gets a message when they try to sort that says “There are too many records to sort
/// – please add more criteria” or something like that.
///

private void MessageforMaxRecords()
{
if (_MaxReocrd != null)
{

if (_dstforSorting.Tables[0].Rows.Count > _MaxReocrd)
{

lblIfRowMoreThanLimit.Text = "There are too many records to sort
– please add more criteria.";
Controls.Add(lblIfRowMoreThanLimit);
Controls.Add(new LiteralControl("[br/]"));


}
}

}

}
}

Tuesday, June 3, 2008

creating custom control for search TextBox and Button and retrun dataset

Hi, here all technical details of creating custom control for search. Search dustom control return dataset on page. We can use this dataset for various database operation on page. At the end of document there is sql statements of creating table and insert values.

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

namespace searchControl
{

public class SearchControl : Control, INamingContainer
{
/// The Control class is the base class for all ASP.NET server controls.

///INamingContainer is a marker interface without method. When a control inherits with INamingContainer,
///the ASP.NET page framework creates a new naming scope under that control,this ensur us that the child
///controls have unique names.

///About our approch of create search Custom Control :-
/// This is Example custom control with possibility of enhancement. we used forecolor, connection string as property
/// similar we can use property of table name.

/// How to use :-
/// Add reff of dll and choose it as a tool. and drag drop on page from tool box.
///
///

/// on CS page :-
/// page load :- this.SearchControl1.ConnectionString = @"Data Source=192.168.0.4\ver2005;Initial Catalog=test_navdeep;User ID=navdeep;Password=navdeep";

/// protected void onSubmitName(object sender, EventArgs e)
/// {
/// DataSet dst = this.SearchControl1.ReturnDataSet;
/// }

#region property and variables

bool handled = false;
private Color _ForeColor;
private string _searchkey;
private string str = string.Empty;
private DataSet dstTest1 = new DataSet();
private string _connectionString = string.Empty;

public string ConnectionString
{
get { return _connectionString; }
set { _connectionString = value; }
}


private SqlConnection conPub;
public string SearchkeyColmunName
{
get { return _searchkey; }
set { _searchkey = value; }
}
private TextBox txtSearchKey; ///Control to add in our composite control

private DataSet dst = new DataSet();
private string _returnDataSet = string.Empty ;


public event EventHandler Submit; /// It's a delegate Eventhandler. The other two data member variables created are actually of type
/// EventHandler. We will be using them for handling the events that
/// are going to be raised by the Button controls
///Similar we can add or more event handler

public Color ForeColor
{
get { return _ForeColor; }

set { _ForeColor = value; }
}

public string SearchKey
{
get
{
this.EnsureChildControls(); ///Determines whether the server control contains child controls.
///If it does not, it creates child controls.
return txtSearchKey.Text;

}

set
{
this.EnsureChildControls();
txtSearchKey.Text = value;

}
}

#endregion property and variables

#region Create design view of control
protected override void CreateChildControls()///Called by the ASP.NET page framework to notify server controls
/// that use composition-based implementation to create any child
/// controls they contain in preparation for posting back or
/// rendering

{

Label lblSearchKey = new Label();
lblSearchKey.Text = "Search Key: ";
lblSearchKey.ForeColor = _ForeColor;
Controls.Add(lblSearchKey);

txtSearchKey = new TextBox();
Controls.Add(txtSearchKey);

Controls.Add(new LiteralControl("
")); /// for breaking a new line



Controls.Add(new LiteralControl("
"));

Button btnSubmit = new Button();
btnSubmit.Text = "Search";
btnSubmit.CommandName = "Submit";
btnSubmit.ForeColor = _ForeColor;
Controls.Add(btnSubmit);

Controls.Add(new LiteralControl(" "));



}
#endregion Create design view of control

#region virtual bubleEvent
protected override bool OnBubbleEvent(object Source, EventArgs Sender)///These methods are OnBubbleEvent and
///RaiseBubbleEvent. We will be using the OnBubbleEvent for our event handling.
///So here is the code for the method that we override for usage within our own class.

{



if (Sender is CommandEventArgs)
{

CommandEventArgs ce = (CommandEventArgs)Sender;

if (ce.CommandName == "Submit") /// if we contain two button on composite then we determine to fire it
/// delepending on its command name on button
{

onSubmit(ce);
handled = true;
}


}

return handled;

}

#endregion virtual bubleEvent

#region onSubmit
protected virtual void onSubmit(EventArgs Sender)
{
if (Submit != null)
{
_returnDataSet = txtSearchKey.Text;


Submit(this, Sender);/// set event handling



}
}
#endregion onSubmit

#region ReturnDataSet
///
/// Search depends on searchkey property and return dataset of desird record.
/// for example we can set ID and Aname for two defferent searches
///

public DataSet ReturnDataSet
{
get {
if (txtSearchKey.Text.ToString() != "")
{
if (_searchkey == "ID")

{


SqlDataAdapter dadAuthors;
dstTest1 = new DataSet();
conPub = new SqlConnection( _connectionString);
dadAuthors = new SqlDataAdapter("Select * From Test1 where id = '" + _returnDataSet + "'", conPub);
dadAuthors.Fill(dstTest1, "Test1");

return dstTest1;

}
if (_searchkey == "Aname")


{
conPub = new SqlConnection(_connectionString);
SqlDataAdapter dadAuthors;
dstTest1 = new DataSet();
dadAuthors = new SqlDataAdapter("Select * From Test1 where Fname = '" + _returnDataSet + "'", conPub);
dadAuthors.Fill(dstTest1, "Test1");


return dstTest1;
}


return dstTest1;
}
else
{


return dstTest1;
}




}
}

#endregion ReturnDataSet



}
}


Table which we used for search


select * from Test1
Create table Test1( ID varchar(50), Fname varchar(50), Lname varchar(50), Address varchar(50), depID varchar(50))
create proc
@id varchar(50),
@Fname varchar(50),
@Lname varchar(50),
@Address varchar(50),
@depID varchar(50)
as
insert into Test1 values(@id,@Fname,@Lname,@Address,@depID)

insertInTO '1', 'A_Fname', 'A_Lname1','A_Address', 'D1'
insertInTO '2', 'B_Fname', 'B_Lname1', 'B_Address', 'D2'
insertInTO '3', 'C_Fname', 'C_Lname1', 'C_Address', 'D3'
insertInTO '4', 'D_Fname', 'E_Lname1', 'F_Address', 'D4'
insertInTO '6', 'E6_Fname', 'E6_Lname1', 'E6_Address', 'D6'
insertInTO '5', 'E_Fname', 'E5_Lname1', 'E5_Address', 'D5'

insertInTO '6','E6_Fname','E6_Lname1','E6_Address','D6'
insertInTO '5','E_Fname','E5_Lname1','E5_Address','D5'
insertInTO '7','7G_Fname','G7_Lname1','G_Address','D7'
insertInTO '8','H8_Fname','E8_Lname1','8F_Address','D8'
insertInTO '9','9I_Fname','I9_Lname1','9I_Address','D9'

insertInTO '10','9I_Fname','I9_Lname1','9I_Address','D10'
insertInTO '11','9I_Fname','I9_Lname1','9I_Address','D11'
insertInTO '12','9I_Fname','I9_Lname1','9I_Address','D12'
insertInTO '13','9I_Fname','I9_Lname1','9I_Address','D13'
insertInTO '14','9I_Fname','I9_Lname1','9I_Address','D14'
insertInTO '15','9I_Fname','I9_Lname1','9I_Address','D15'
insertInTO '16','9I_Fname','I9_Lname1','9I_Address','D16'
insertInTO '17','9I_Fname','I9_Lname1','9I_Address','D17'