Google Search

Google
 
Showing posts with label Tips -Tricks. Show all posts
Showing posts with label Tips -Tricks. Show all posts

Wednesday, May 28, 2008

Find Nth highest salary from table

In interview you can faced question like to give solution(query) for find Nth highest salary from given employee table.

TO find out 3rd highest salary from table

--Find 3rd highest salary
SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP 3 salary
FROM tblSalary
ORDER BY salary DESC) S
ORDER BY salary

General form to find to Nth highest salary from table

--Find Nth highest salary
SELECT TOP 1 salary FROM (
SELECT DISTINCT TOP N salary FROM tblSalary ORDER BY salary DESC) S
ORDER BY salary

There are many solution to solve to this but above solution is easiest.
Take other possible solution,

SELECT MIN(salary) FROM tblSalary WHERE salary IN
(SELECT DISTINCT TOP 3 salary FROM tblSalary ORDER BY salary DESC)

--or--

SELECT MIN(salary) FROM
(SELECT DISTINCT TOP 3 salary FROM tblSalary ORDER BY salary DESC) S

Tuesday, February 26, 2008

Enable/Disable RequiredFieldValidator with Javascript

Sometimes we need to Enable or Disable validation on client side.For that use ValidatorEnable function in the Asp.net javacsript Script Library.

For that set EnableClientScript property of validator to True.

Here i give example for this:

I have a page with a couple of radio buttons.On radio button selection i want to enable/disable validation.

In example if i select Email radio button then Email div will display and only txtEmail textbox validator is enabled.

Java Script for this:

<script language="JavaScript" type="text/javascript">
function autoSelect(control,type)
{
if(type=="Email")
{
document.getElementById('Email').style.display="block";
document.getElementById('PhoneNo').style.display="none";
ValidatorEnable(document.getElementById("RequiredFieldValidator1"), true);
ValidatorEnable(document.getElementById("RequiredFieldValidator2"), false);

}
else
{
document.getElementById('Email').style.display="none";
document.getElementById('PhoneNo').style.display="block";
ValidatorEnable(document.getElementById("RequiredFieldValidator1"), false);
ValidatorEnable(document.getElementById("RequiredFieldValidator2"), true);
}
}
</script>

Code for this:


Email :
<input type="radio" id="RadioButton1" runat="server" value="Plan1" name="Plan" onclick="autoSelect(this,'Email')" checked />
PhoneNo :
<input type="radio" id="RadioButton2" runat="server" value="Plan1" name="Plan" onclick="autoSelect(this,'PhoneNo')" />
<div id="Email">
Email <asp:TextBox ID="txtEmail" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Email Required"
ControlToValidate="txtEmail" EnableClientScript="true" ValidationGroup="vgSubmit" />
</div>
<div id="PhoneNo" style="display:none">
PhoneNo <asp:TextBox ID="txtPhoneNo" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="PhoneNo Required"
ControlToValidate="txtPhoneNo" EnableClientScript="true" ValidationGroup="vgSubmit"/>
</div>
<asp:Button ID="btnSubmit" runat="server" Text="Button" ValidationGroup="vgSubmit"/>

Tuesday, January 22, 2008

DateTime Formatting in GridView,DetailView,FormView

In Asp.Net 2.0 direct datetime formatting for bound column not possible.

To format column into datatime you have to set HtmlEncode="False" property of BoundField.


The Reason behind for this is bydefault data is Html Encoded that prevents to format date.So, set HtmlEncode to False.

Saturday, January 5, 2008

File Download dialog box

Code to open a "save as.." file download dialog box in asp.net 2.
Here,I create a vb.net function for to open file download dialog box.

Use System.IO class for file system. Function argument accepts a File virtual path not physical path.

This code for only .txt file but you also use this code for more extension file.For that change only ContentType.

.htm,.html => "text/HTML"
.txt => "text/plain"
.doc,.rtf => "Application/msword"
.csv,.xls => "Application/x-msexcel"
.pdf =>"Application/pdf"


Function DisplayDownloadDialog(ByVal PathVirtual As String)

Dim strPhysicalPath As String
Dim objFileInfo As System.IO.FileInfo
Try
strPhysicalPath = Server.MapPath(PathVirtual)
'exit if file does not exist
If Not System.IO.File.Exists(strPhysicalPath) _
Then Exit Function
objFileInfo = New System.IO.FileInfo(strPhysicalPath)

Response.Clear()
Response.ClearHeaders()
Response.ClearContent()
'Add Headers to enable dialog display
Response.AddHeader("Content-Disposition", "attachment; filename=" & _
objFileInfo.Name)
Response.AddHeader("Content-Length", objFileInfo.Length.ToString())

Response.ContentType = "Text / plain"

Response.WriteFile(objFileInfo.FullName)


Catch
'on exception take no action
'you can implement differently
Finally

Response.End()

End Try
End Function

Sunday, December 2, 2007

Find ASP.NET Child Controls

To find out child control from parent control we use "$" acts as the delimiter.

Syntax for find out child control from parent control is parentControlID$childControlID.

Here, I give example to DefaultFocus attribute of the < form > element to set the focus to a TextBox nested within a FormView control.

< form id="form1" runat="server" DefaultFocus="vwTest$txtName" >
< div >
< asp:FormView ID="vwTest" runat="server" >
< ItemTemplate >
Name:
< asp:TextBox ID="txtName" runat="server"
Text='<%# Eval("FirstName") + " " + Eval("LastName") %>' / >
< /ItemTemplate >
< /asp:FormView >
< /div >
< /form >

Notice that the DefaultFocus attribute refers to the parent control first (the FormView) and then to the child control (the TextBox) using the vwTest$txtName syntax.

Find ASP.NET Child Controls

To find out child control from parent control we use "$" acts as the delimiter.

Syntax for find out child control from parent control is parentControlID$childControlID.

Here, I give example to DefaultFocus attribute of the < form > element to set the focus to a TextBox nested within a FormView control.

< form id="form1" runat="server" DefaultFocus="vwTest$txtName" >
< div >
< asp:FormView ID="vwTest" runat="server" >
< ItemTemplate >
Name:
< asp:TextBox ID="txtName" runat="server"
Text='<%# Eval("FirstName") + " " + Eval("LastName") %>' / >
< /ItemTemplate >
< /asp:FormView >
< /div >
< /form >

Notice that the DefaultFocus attribute refers to the parent control first (the FormView) and then to the child control (the TextBox) using the vwTest$txtName syntax.

Friday, August 31, 2007

MaxLength in TextBox control in ASP.Net

When I was use TextBOx with TextMode "MultiLine" and MaxLength "10".I can enter more than 10 characters. SO I use Java Script for that and it solve my problem.

JavaScript like this :

< script language="javascript" >
function limitCharsLength(Object, MaxLen)
{
return (Object.value.length <= MaxLen-1);
}
< /script >


and TextBox like this :

< asp:TextBox ID="TextBox1" runat="server" Height="173px" TextMode="MultiLine"
Width="369px" onkeypress="javascript: return limitCharsLength(this,5);"
onblur="javascript: limitCharsLength(this, 5)"
onchange="javascript : return limitCharsLength(this, 5)" >< /asp:TextBox >

Tuesday, May 29, 2007

Imporve Performance Of Web Site

1. Maintain the position of the scrollbar on postbacks: In ASP.NET 1.1 it was a pain to maintain the position of the scrollbar when doing a postback operation. This was especially true when you had a grid on the page and went to edit a specific row. Instead of staying on the desired row, the page would reload and you'd be placed back at the top and have to scroll down.

2. Set the default focus to a control when the page loads: This is another extremely simple thing that can be done without resorting to writing JavaScript. If you only have a single textbox (or two) on a page why should the user have to click in the textbox to start typing? Shouldn't the cursor already be blinking in the textbox so they can type away? Using the DefaultFocus property of the HtmlForm control you can easily do this.

3. Set the default button that is triggered when the user hits the enter key: This was a major pain point in ASP.NET 1.1 and required some JavaScript to be written to ensure that when the user hit the enter key that the appropriate button on the form triggered a "click" event on the server-side. Fortunately, you can now use the HtmlForm control's DefaultButton property to set which button should be clicked when the user hits enter. This property is also available on the Panel control in cases where different buttons should be triggered as a user moves into different Panels on a page.

4. Validation groups: You may have a page that has multiple controls and multiple buttons. When one of the buttons is clicked you want specific validator controls to be evaluated rather than all of the validators defined on the page. With ASP.NET 1.1 there wasn't a great way to handle this without resorting to some hack code. ASP.NET 2.0 adds a ValidationGroup property to all validator controls and buttons (Button, LinkButton, etc.) that easily solves the problem. If you have a TextBox at the top of a page that has a RequiredFieldValidator next to it and a Button control, you can fire that one validator when the button is clicked by setting the ValidationGroup property on the button and on the RequiredFieldValidator to the same value. Any other validators not in the defined ValidationGroup will be ignored when the button is clicked.

Monday, May 28, 2007

String Functions in .NET

Several built-in string functions perform string manipulations to augment simple concatenation with the "&" operator.

Function in ASP.NET

Asc() Returns the character code of the first character of a string.

Asc("A") returns 65.

Chr() Returns the display character of a character code.

Chr(65) returns "A".

GetChar() Returns the character at a specified position in a string, counting from 1.

GetChar("This is a string", 7) returns "s".

InStr() Returns the starting position in a string of a substring, counting from 1.

InStr("This is a string", "string") returns 11.

InStrRev() Returns the starting position in a string of a substring, searching from the end of the string.

InStr("This is a string", "string") returns 11.

LCase() Returns the lower-case conversion of a string.

LCase("THIS IS A STRING") returns "this is a string".

Left() Returns the left-most specified number of characters of a string.

Left("This is a string", 4) returns "This".

Len() Returns the length of a string.

Len("This is a string") returns 16.

LTrim() Removes any leading spaces from a string.

LTrim(" This is a string") returns "This is a string".

Mid() Returns a substring from a string, specified as the starting position (counting from 1) and the number of characters.

Mid("This is a string", 6, 4) returns "is a".

Replace() Replaces all occurences of a substring in a string.

Replace("This is a string", " s", " longer s") returns "This are a longer string" (replaces an "s" preceded by a blank space).

Right() Returns the right-most specified number of characters of a string.

Right("This is a string", 6) returns "string".

RTrim() Removes any trailing spaces from a string.

RTrim("This is a string ") returns "This is a string".

Str() Returns the string equivalent of a number.

Str(100) returns "100".

Space() Fills a string with a given number of spaces.
"This" & Space(5) & "string" returns "This string".

StrComp() Compares two strings. Return values are 0 (strings are equal), 1 (first string has the greater value), or -1 (second string has the greater value) based on sorting sequence.

StrComp("This is a string", "This string") returns -1.

StrReverse() Reverses the characters in a string.

StrReverse("This is a string") returns "gnirts a si sihT".

Trim() Removes any leading and trailing spaces from a string.

Trim(" This is a string ") returns "This is a string".

UCase() Returns the upper-case conversion of a string.

UCase("This is a string") returns "THIS IS A STRING".

Val() Converts a numeric expression to a number.

Val( (1 + 2 + 3)^2 ) returns 36.

Mathematical Functions in .NET

Popular mathematical functions are summarized in the following table. Note that certain functions do not require the Math. prefix.

Mathematical Function in .NET

Math.Abs() Returns the absolute value.

Math.Abs(-10) returns 10.

Math.Ceiling() Returns an integer that is greater than or equal to a number.

Math.Ceiling(5.333) returns 6.

Fix() Returns the integer portion of a number.

Fix(5.3333) returns 5.

Math.Floor() Returns an integer that is less than or equal to a number.

Fix(5.3333) returns 5.

Int() Returns the integer portion of a number.

Int(5.3333) returns 5.

Math.Max() Returns the larger of two numbers.

Math.Max(5,7) returns 7.

Math.Min() Returns the smaller of two numbers.

Math.Min(5,7) returns 5.

Math.Pow() Returns a number raised to a power.

Math.Pow(12,2) returns 144.

Rnd() Returns a random number between 0 and 1. Used in conjunction with Randomizestatement to initialize the random number generator.

Math.Round() Rounds a number to a specified number of decimal places. Rounds up on .5.

Math.Round(1.1234567,5) returns 1.12346.

Math.Sign() Returns the sign of a number. Returns -1 if negative and 1 if positive.

Math.Sign(-5) returns -1.

Math.Sqrt() Returns the square root of a positive number.

Math.Sqrt(144) returns 12.