ASP.NET (35) SQL (25) JAVASCRIPT (24) HTML (14) STYLE SHEET (6) ASP (4) SCRIPT (1)

Search me out HERE!!

Fill DATASET from Cache in ASP.net

Below code will show how to fill DataSet from cache instead of getting data each time from Database:


public DataSet load_data()
    {
        DataSet ds;
        if (Cache["test"] == null)
        {
            SqlConnection cn = new SqlConnection("server=.;database=pubs;uid=sa;password=;");
            cn.Open();
            SqlDataAdapter cmd = new SqlDataAdapter("select * from test",cn);
            ds = new DataSet();
            cmd.Fill(ds, "test");
            Cache.Insert("test", ds, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5));
            cn.Close();
        }
        else
        {
            ds = (DataSet)Cache["test"];
        }
        return ds;
    }

You can get your Dataset by just calling load_data() method as given below:
DataSet ds = load_data();

Add to BOOK MARK using Javascript

Below JavaScript can be used to set Book Mark link

JAVASCRIPT:
<script type="text/javascript">
function bookmarksite(title,url){
if (window.sidebar) // firefox
    window.sidebar.addPanel(title, url, "");
else if(window.opera && window.print){ // opera
    var elem = document.createElement('a');
    elem.setAttribute('href',url);
    elem.setAttribute('title',title);
    elem.setAttribute('rel','sidebar');
    elem.click();
}
else if(document.all)// ie
    window.external.AddFavorite(url, title);
}
</script>


HTML CODE:
<a href="javascript:bookmarksite('Google', 'http://www.google.com')"> Add to Favorites </a>

To Send Mail in ASP.NET With C# using GMAIL Account

Below code can be used in ASP.net with C# to send email using your Gmail Account.

string from = me@gmail.com; //Replace this with your own correct Gmail Address
string to = to@abc.com //Replace this with the Email Address to whom you want to send the mail

System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from, "Admin" , System.Text.Encoding.UTF8);
mail.Subject = "This is a test mail" ;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "This is Email Body Text";
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true ;
mail.Priority = MailPriority.High;

//Add the Creddentials- use your own email id and password
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential(from, "Password");

client.Port = 587; // Gmail works on this port
client.Host = "smtp.gmail.com";
client.EnableSsl = true; //Gmail works on Server Secured Layer
try
{
    client.Send(mail);
}
catch (Exception ex)
{
    HttpContext.Current.Response.Write(ex2.ToString());
} // end try

GET Various parts of Date, Year, Month, Day from Date in SQL

Below function can be used in your query to get Year, Month, Day of date separated from Date.


SELECT year(from_date) AS yyyy, month(from_date) as mm, day(from_date) as dd FROM test

Note: Here test is table and from_date is field with DateTime datatype.

To Fetch FORM Element value directly in JAVASCRIPT

Below example show how to fetch Form Element value directly in Javascript without use of Document.form

JAVASCRIPT:
<script language="javascript">
function checkTestForm()
{
    with (window.document.frmTest)
    {
        alert(txtPrice.value);       
    }
   
}

</script>

HTML CODE:
<form id="frmTest" name="frmTest" method="post">
<input type="text" id="txtPrice" name="txtPrice" />
<input type="button" id="btn" name="btn"  value="OK"   onclick="return checkTestForm();" />
</form>

To know your computer DRIVE Space using SQL Server

Just copy below code and execute in your SQL Server, you will get your Driver free Space:

DECLARE @OSDriveSpace TABLE
(
  DriveNm char(1),
  FreeDriveSpaceInMB int
)

INSERT INTO @OSDriveSpace
EXEC master.dbo.xp_fixeddrives

SELECT *  FROM @OSDriveSpace

How to provide Simple Custum Error Page in ASP.Net using web.config

Below code need to be included in web.config file
Note : There is already customErrors Tag in Web.config file, you need to replace that.

<system.web>
<customErrors mode="On" defaultRedirect="error.aspx"></customErrors> 
</system.web>

Here error.aspx is page where you can mention your Error Message, which will be shown every time when exception will occur in your project.

How to extract value of GROUP CHECK BOX in PHP

Below given is PHP script to get value of Selected CHECK BOX from group of CHECK BOX and HTML Code for Group of CHECK BOX

$checkbox_value ="";
$temp =$_POST['test_cb'];

while (list ($key,$val) = @each ($temp)) {
$checkbox_value .= "$val,";
}
?>

<input type="checkbox" name="test_cb[]" value="Test1" />Test1
<input type="checkbox" name="test_cb[]" value="Test2" />Test2

How to clear recent project list in VISUAL STUDIO

Follow below given Steps:
  1. Close Visual Studio if it is running.
  2. Start the Registry Editor (Type regedit in Start->Run).
  3. Navigate to this registry key:
    HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\ProjectMRUList
  4. Then delete the key that has the project you do not want to keep in the list.

NOTE : Check in all VisualStudio / 5.0 or 8.0 or 9.0, if you dont find project list.

Progress Bar in Update Panel in C#

Use below Code to have Progress Bar in ASP.net with C# using AJAX


<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table>
<tr>
<td>
<asp:UpdateProgress runat="server" ID="UpdateProgress1" 
DynamicLayout="false" AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<img id="Img1" runat="Server" src="<Path of Gif or motion image file>" height="12"  alt=""/>
</ProgressTemplate>
</asp:UpdateProgress>
</td>
</tr> 
<tr>
<td><asp:Button CssClass="button" Text="Search" runat="server" ID="NewPage" />              
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>

To Create WORD FILE and write in it in PHP

Below code is to create WORD file and then write in it. Its simple form, and value entered in Textbox will be written in WORD file.

<?
if($_POST)
{   
    $fp = fopen("test.doc", 'w+');
    $str = "First Name: " .$_POST['fname']."\n";
    $str .= "Middle Name: " .$_POST['mname']."\n";
    $str .= "Last Name: " .$_POST['lname']."\n";
    fwrite($fp, $str);
    fclose($fp);
}
?>

<form method="post">
First Name : <input type="text" name="fname"><br />
Middle Name : <input type="text" name="mname"><br />
Last Name : <input type="text" name="lname"><br />
<input type="submit" name="submit">
</form>

Setting TEXTBOX Background Image and Color Using JavaScript & CSS

Consider below textbox:
<input type="text" id="textbox_name" />

Now you can apply BACKGROUND COLOR or BACKGROUND IMAGE using below JAVASCRIPT or CSS
// USING STYLE CSS
.textbox
{
background-color:#FFFFFF;
background:url(images/test.jpg);
}

// USING JAVASCRIPT
function set_background
{
document.getElementById('textbox_name').style.backgroundColor = '#FFFFFF'; document.getElementById('textbox_name').style.backgroundImage="url(images/test.jpg)";
}

TO FIND BROWSER USING JAVASCRIPT

Using below JavaScript you can get information about browser.

<script language="JavaScript" type="text/javascript">
var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;    // For IE
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;  // For Firefox
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;  // For Opera
alert(isIE);
alert(isWin);
alert(isOpera);
</script>

Count Number of letter in Textarea or Textbox using Javascript

Kindly write anything in Textbox:


Characters left

Code:
Javascript Function:
<script language="javascript">
function textCounter(field,cntfield,maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else
cntfield.value = maxlimit - field.value.length;
}
</script>


HTML
<form name="frm">
<textarea name="comments" id="comments" cols="30" rows="4" wrap="physical" onKeyDown="textCounter(document.frm.comments,document.frm.remLen1,100)"onKeyUp="textCounter(document.frm.comments,document.frm.remLen1,100)" tabindex="14"> </textarea>
<br />
<input readonly type="text" name="remLen1" style="border:0; width:30px;" size="3" maxlength="3" value="100"> Characters left
</form>


Calendar using Javascript


DEMO:

Date: 


   (Click in Textbox)

Click on below link to Download .js file
Click Here

Code for HTML Page
<script language="javascript" type="application/javascript" src="scw.js"></script>

Date:<input  type="text" name="test" onselect='scwShow(this,event);' onclick='scwShow(this,event);' readonly="readonly" />

To apply COMMON CSS to all Textbox, Radio Button, Checkbox

Below CSS can be used to apply to all TEXTBOX, RADIO BUTTON or CHECK BOX without giving class.

CODE to be implemented in style.css file:

input[type=text] 
{
//Here will be property as per requirement. 
}

input[type=radio] 
{
//Here will be property as per requirement.
}


input[type=checkbox] 
{
//Here will be property as per requirement. 
}

Same way you can apply CSS to any input type.

How to disable HTML attribute using JAVASCRIPT

Below JavaScript can be used to disable HTML Attributes during run time. (Eg: TextBox, Select Box, Check Box, Radio Button, Etc)

<script>
window.onload= function()
{
          DisableEnableForm(document.frmwitness,true);
 }

function DisableEnableForm(xForm,xHow){
  objElems = xForm.elements;
  for(i=0;i
  {
       var ck = objElems[i].type;
       if(ck=="select-one" || ck=="text")
      {
          objElems[i].disabled = xHow;
       }
   }
}
</script>


Note: You can call above function as per requirement.

VALIDATE FILE EXTENSION USING JAVASCRIPT

This Javascript can be used to allow only few file extension only.

Include Below Script
<script>
    function validateFileExtension(fld)
    {
        if(!/(\.zip|\.rar|\.doc|\.docx|\.ppt|\.xls|\.xlsx|\.pptx|\.jpg|\.jpeg|\.pdf)$/i.test(fld.value))         

       {
            alert("Invalid image file type.");
            fld.value='';
            fld.focus();
            return false;
        }
        return true;
    }

</script>

Call above function in HTML as given below:
<input type="file" name="uploadFile1" id="uploadFile1" onchange="return validateFileExtension(this)" />

Note:
Here as mention in Javascript only file with .zip, .rar, .doc, .docx, .ppt, .xls, .xlsx, .pptx, .jpg, .jpeg, .pdf  will be allowed. This can be changed as per requirement.

Allow only numeric value through Javascript

Below JavaScript will allow only to enter numeric value in Textbox. This javascript can be used for Mobile number, Salary, Budget, etc.

Include below JavaScript
<script language="javascript" type="text/javascript">
function isNumber(field)
{
    var textbox = document.getElementById(field);
    var re = /^[0-9]*$/;
    if (!re.test(textbox.value))
    {
        textbox.value = textbox.value.replace(/[^0-9]/g,"");
    }
}

</script>

Call this fuction in HTML as given below:
<input type="text" name="test" id="test" onkeyup="isNumber('test');" />

HOW TO GET POSITION OF PARTICULAR OBJECT USING JAVASCRIPT

Below JavaScript function is used to get position of any object.

function findPos()
{
      //Here 'myTextbox' is object whose position is calculated.
      obj = document.getElementById('myTextbox');
      var posX = obj.offsetLeft;
      var posY = obj.offsetTop;
      while(obj.offsetParent)
     {
      posX=posX+obj.offsetParent.offsetLeft;
      posY=posY+obj.offsetParent.offsetTop;
      if(obj==document.getElementsByTagName('body')[0]){break}
      else{obj=obj.offsetParent;}
      }
//posX and posY are postion of required object.
}

Changing image on mouse hover in anchor tag

Below code is used to change IMAGE in anchor code on Mouse Hover.

Include Below SCRIPT:
<script language="javascript" type="text/javascript">
/**
 * flip(imgName, imgSrc) sets the src attribute of a named
 * image in the current document. The function must be passed
 * two strings. The first is the name of the image in the document
 * and the second is the source to set it to.
 **/
function flip(imgName, imgSrc){
   if (document.images){
      document[imgName].src = imgSrc
   }
}
</script>


Now you code for ANCHOR Tag will be:
<a HREF="nextPage.html" onMouseOver="flip('Register', 'images/test_hover.gif')"
     onMouseOut ="flip('Register', 'images/test.gif')">                               
     <img src="images/test.gif" alt="Register" name="Register" width="185" border="0">

</a>

Note: Here test.gif is visible by default and test_hover image will be visible on Mouse Hover.

BULK INSERT INTO TABLE FROM COMMA SEPERATED .txt FILE IN SQL

Below code can be used in SQL SERVER 2005 to insert bulk value in Table from .txt file (Values are separated by comma ',' ).

BULK
INSERT testing_table
FROM 'c:\testing.txt'
WITH
(
    FIELDTERMINATOR = ',',
    ROWTERMINATOR = '\n'
)

GO

Note : c:/testing.txt is file from which data need to be uploaded. Also here testing.txt file will contain values with ',' separator and new row is in new line.

TO SET VISIBILITY OF VARIOUS ITEMS IN .rdlc REPORT IN ASP.Net DURING RUN TIME

Select the Object for which you want to set visibility on Run Time. Then in Property section there in Property name 'VISIBILITY', in that set HIDDEN Expression as given below:

=iif(Fields!test.Value.ToString().Equals("true"),true,false)

If this expression is TRUE then that object will not be visible. By default its HIDDEN value is set to FALSE.
So if certain object need to be made invisible then pass "true" in dataset, which can be checked in if condition & hence HIDDEN property can be changed accordingly.

In Above example i have passed value in 'test'. If 'test' is true, then object will be not be visible and if 'test' is false then object will be visible.

CONVERT STRING INTO FLOAT WITH FIX DECIMAL PLACES IN ASP.NET

Below code is used to get float number in fix decimal places:


float flag;
flag = float.Parse(string.Format("{0:0.00}", number));

Eg:
number = 3.453432;
flag = float.Parse(string.Format("{0:0.00}", number));
// output : flag=3.45

TO USE GLOBAL PARAMETER FROM WEB.CONFIG FILE

Below mention is code to access Connection string from Web.Config file. Here you can have multiple variables.

Write this in Web.Config file :


<configuration> 
  <appSettings> 
     <add key="ConnectionString" value="server=localhost;uid=sa;pwd=;database=DBPerson" /> 
  </appSettings>
</configuration>

//Here value is Connection String used to connect with database
 Now you can access above value in your web page as given below: 
using System.Configuration;
string connectionString = ConfigurationSettings.AppSettings["ConnectionString"].ToString();


Note:Similarly you can add multiple KEY which you want as global variable.

Various tab to INCLUDE IN HEAD part for SEO and better search result

Below tags should be included in Head part with proper content to get SEO.

<meta name="google-site-verification" content="" ></meta>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" ></meta>
<meta name="Author" content="COMPANY NAME" ></meta>
<meta name="Keywords" content="Here comes various keywords with ',' separator" ></meta>
<meta name="description" content="HERE COMES YOUR DESCRIPTION" ></meta>
<meta name="Copyright" content="? 2009-2010 www.website.com"></meta>
<meta name="Publisher" content="Company name." ></meta>
<meta name="document-classification" content="TAG LINE" ></meta>
<meta name="document-type" content="Public" ></meta>
<meta name="document-distribution" content="Global" ></meta>
<meta name="robots" content="ALL, INDEX, FOLLOW"></meta>
<meta name="googlebot" content="index, follow" ></meta>
<meta name="revisit-after" content="7 Days" ></meta>
<meta name="Expires" content="never" ></meta>

From above, it is not necessary to include all META tags. Basic and important META tag are KEYWORDS & DESCRIPTION

POP UP WINDOW USING JAVASCRIPT

Following Javascript function is used to pop up new window when we click on any link:

PUT THIS FUNCTION IN JAVASCRIPT
function showevent ()
{
          window.open("test.html", "nw",'titlebar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,top=120,left=200,width=600,height=400')

}

NOW ON LINK TAG. i.e. A TAG, ADD
<a href="javascript:showevent();" >OPEN WINDOW</a>


Whenever we will click on LINK, test.html page will open. Here any page instead of test.html can be used, which you want to POP UP.

Refreshing parent window from child window

Below Javascript is used to refresh PARENT window from CHILD window, also CHILD window will be closed.

//Call below Javascript on CLOSE button click in CHILD window
JAVASCRIPT FUNCTION:

function change_parent(){
window.opener.location.href="http:yahoo.com";
self.close();
}
 

Now call this Javascript on your button
onClick="change_parent();"

You will see that when you close your child window your parent page will redirect to 'yahoo.com' 

HOW TO USE CASE IN SQL SERVER 2005

Below is syntax to use CASE in SQL Server 2005

Syntax:
SELECT
CASE
    WHEN CONDITION THEN
            DATA                  
        ELSE
            DATA
    END AS column_name
FROM tableName


Example:
SELECT
CASE
        WHEN SIGN(DATEDIFF(dd,GETDATE(),any_date)) = '1' THEN
            DATEDIFF(dd,GETDATE(),any_date)                  
        ELSE
            SIGN(0)
    END AS column_name
FROM any_table 


Note : You can use number of WHEN condition before ELSE

SHOW ROW NUMBER IN GRIDVIEW

Below code is used in .aspx file to get ROW NUMBER in gridview.

<asp:TemplateField HeaderText="No.">
                    <ItemTemplate>
                      
<center><%# Container.DataItemIndex + 1 %></center>
                    
</ItemTemplate>
</asp:TemplateField>



E-MAIL VALIDATION USING JAVASCRIPT

Below javascript is used to valid email address using Regular Expression.
function validate()
{
   //Here 'form1' is name of form. & 'email' is name of Email Text box.
   var address = document.form1.email.value;
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(address) == false) {
              alert('Invalid Email Address');
              document.form1.email.focus();
              return false;
            }

   return true;
}

How to find ROW in Dataset / Applying PRIMARY KEY to Dataset

Here is solution how you can apply primary key to your DATASET & using that how can you find particular row from Dataset using that Primary Key.

Note the below given code:

DataSet ds = new DataSet();
DataColumn[] dc = new DataColumn[1];  
//HERE '1' SPECIFY NO. OF PRIMARY KEY. YOU CAN HAVE MORE THEN 1 PRIMARY KEY.
dc[0] = ds.Tables[0].Columns["id"];  //id is Primary Key
ds.Tables[0].PrimaryKey = dc;


Now you can get ROW as given below:

DataRow dr = ds.Tables[0].Rows.Find("1"); 

//Here "1" Specify Primary key.. i.e. Here output will be row whose id=1.

How to Get ROUND BOX in Website Designing.

Kindly see the below images. To get the round box you need to CUT box into various pieces as shown in below Image.
HERE I HAVE ALSO SHOWN HOW TO DISPLAY NAME IN BETWEEN. THIS IS OPTIONAL.




Now go with below given code.


CODE:
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="background:url(images/top_left.gif); background-repeat:no-repeat; width:19px; height:37px;"></td>
<td style="background:url(images/top_middle.gif); background-repeat:repeat-x; height:37px;" align="left">
<img align="top" src="images/kapil.gif" border="0" height="37px" />
</td>
<td style="background:url(images/top_right.gif); background-repeat:no-repeat; width:19px; height:37px;"></td>
</tr>

<tr>
<td style="background:url(images/middle_left.gif); background-repeat:repeat-y; width:19px; " ></td>
<td>

<table cellpadding="0" cellspacing="0" width="100%">
<tr>
<td>
THIS IS TEXT AREA
</td>
</tr>
</table>

</td>
<td style="background:url(images/middle_right.gif); background-repeat:repeat-y; width:19px; "></td>
</tr>

<tr>
<td style="background:url(images/bottom_left.gif); background-repeat:no-repeat; width:19px; height:20px;"></td>
<td style="background:url(images/bottom_middle.gif); background-repeat:repeat-x; height:20px;"></td>
<td style="background:url(images/bottom_right.gif); background-repeat:no-repeat; width:19px; height:20px;"></td>
</tr>
</table>


After applying this, you will get below given Output:

How to get SMALL icon on Tab when we Browse our Site.

This is FAVICON Icon. You just need to create this icon, with Extention .ico Then include below code in Head Tag. You will get Small Icon which you see on TAB when we Browse any website.

< link rel="shortcut icon" href="favicon.ico" />
YOU CAN ALSO USE .gif or .jpg IMAGE, BUT MAKE SURE THAT ITS SIZE IS SMALL (16 * 16)  

FIND DIFFERENCE BETWEEN TWO DATES IN HOURS, MINUTES, SECONDS..

This query will help you to find out difference between two dates in Hours, Minutes, Seconds in SQL Server.


DECLARE @First datetime
DECLARE @Second datetime
SET @First = '04/17/2008 08:00:00'
SET @Second = getdate()

SELECT DATEDIFF(hour,@First,@Second) as TotalHours,
DATEDIFF(minute,@First,@Second) - (DATEDIFF(hour,@First,@Second) * 60) as TotalMinutes,
DATEDIFF(second,@First,@Second) - (DATEDIFF(minute,@First,@Second) * 60) as TotalSeconds

Confirm delete for GridView's CommandField using JavaScript

This CODE will help you to implement Confirm (Using Javascript) When click on DELETE in GRIDVIEW

For this you need to use asp:linkbutton

CODE For Gridview in test.aspx file is

<asp:gridview id="gv_test" onrowdatabound="gv_test_OnRowDataBound" runat="server" >

< columns >
< asp:templatefield headertext="Delete" >
< itemtemplate >

< asp:linkbutton commandargument='<%# Eval("id") %>' commandname="cmdDelete" id="btnDelete" onclientclick="javascript: return confirm('do u want to delete this record')" runat="server" >  DELETE  </ asp:linkbutton >

</ itemtemplate >
</ asp:templatefield >
</ columns >


CODE for  gv_test_OnRowDataBound Method in test.aspx.cs File is

protected void GridView1_RowCommand(object sender,  GridViewCommandEventArgs e)
    { 

//Through command  Name link Button will be identified.
        if (e.CommandName == "cmdDelete")
        {
            // This is id which you can use for DELETE purpose.
            string id = e.CommandArgument;
                       
        }
    }


Using above code you can get confirm before Delete in GRIDVIEW as given below:



How to get inserted ID after we fire INSERT Query.

Here is the solution which will give you ID of record which is recently inserted in SQL.

select @@identity as id

You can check this Query after INSERT statement. So you will get the ID of new row inserted.

Set OPACITY of image / Div tag.

Set OPACITY of image/Div tag.

~  for IE ~
filter:alpha(opacity=60);
~ CSS standard ~
  opacity:0.6;

 Consider below example:

<img src="test.jpg" width="150" height="113" alt="Opacity Test"
style="opacity:0.4;filter:alpha(opacity=40)" />


Regular Image:


The same image with transparency:

Get LOG value of any Number with any Base

Here is JavaScript Code which will help you to get Logarithm Value of any Number with Any Base.

Consider below code

Alert(Math.log(2)/Math.log(10));

NOTE: Here 2 is Number & 10 is Base.

Above code will give Log 2 Value with Base 10

Play VIDEO in ASP.net With C#

Here is the code which will help you to play video in ASP.net using C#

Just open your design page.
default.aspx

Put below code in it:

<object height="150px" width="200px" type ="video/x-ms-wmv" >
<param name="src" value="movie/test.wmv" />
<param name="AutoStart" value="False" />
</object>



Here test.wmv is the video which you want to play.

Your Output Will be:

Stop Further Execution in ASP.net (with C#)

Question : How to stop further execution in ASP.net in page_load, button_click, or any other method.

Answer:
return;

Just put return wherever you want to stop execution. The control will return back and your page will not be further executed.

Retrieve DATE in various format through SQL Query

Below query is used to retrieve DATE in required format through SQL Query.

'SELECT CONVERT(VARCHAR(100),FieldName, 101) AS Sample_date FROM tableName'

Here note that FieldName must of DATETIME or DATE Datatype. Also note that output will be in STRING or VARCHAR Datatype.

You can try out with 100 to 116 Different date format as per your requirement.

ROUND UP "FLOAT" Value in SQL Query.

Below query shows how to round up FLOAT datatype field in SQL Query itself.

SELECT ROUND(FieldName,2) AS TEST FROM TableName

Here there will be '2' digits after decimal point. You can change this number as per your requirement.

Use of ISNULL in SQl Server

Here is the solution to replace NULL with some value in Query itself.
Consider following table:

TESTING

No Data
1 ASP.NET
2 PHP
3 null

Now Run this Query
SELECT ISNULL(data,'0') AS RESULT FROM TESTING

OUTPUT WILL BE:
No Data
1 ASP.NET
2 PHP
3 0

How to use REPLACE & TRANSLATE in SQL Server

Here is the Solution how you can replace Character or Word in SQL QUERY itself.
Query:

SELECT REGCODE, REGTYPE, TRANSLATE(REGTYPE,'R','K') AS RESULT1, REPLACE(REPLACE(REGTYPE,'R4','FOUR'),'R5','FIVE') AS RESULT2 FROM REGION
GO

Here in output REPLACE column will be displayed in which as per required we can replace our desired value in column depending on value of particular column.

OUTPUT
REGCODE REGTYPE RESULT1 RESULT2
1 R4 K4 FOUR
1 R5 K5 FIVE

CONVERT NUMBER INTO WORD IN C# APPLICATION


public string IntegerToWords(long inputNum) {
int dig1,dig2,dig3,level=0,lasttwo,threeDigits;

string retval="";
string x="";
string[] ones={
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen"
};
string[] tens={
"zero",
"ten",
"twenty",
"thirty",
"forty",
"fifty",
"sixty",
"seventy",
"eighty",
"ninety"
};
string[] thou={
"",
"thousand",
"million",
"billion",
"trillion",
"quadrillion",
"quintillion"
};

bool isNegative=false;
if (inputNum < 0) { isNegative=true; inputNum*=-1; } if (inputNum==0) return ("zero"); string s=inputNum.ToString(); while (s.Length>0) {
// Get the three rightmost characters
x=(s.Length<3) ? s : s.Substring(s.Length - 3, 3); // Separate the three digits threeDigits=int.Parse(x); lasttwo=threeDigits % 100; dig1=threeDigits / 100; dig2=lasttwo / 10; dig3=(threeDigits % 10); // append a "thousand" where appropriate if (level>0 && dig1+dig2+dig3>0) {
retval=thou[level] + " " + retval;
retval=retval.Trim();
}

// check that the last two digits is not a zero
if (lasttwo>0) {
if (lasttwo<20) // if less than 20, use "ones" only retval=ones[lasttwo] + " " + retval; else // otherwise, use both "tens" and "ones" array retval=tens[dig2] + " " + ones[dig3] + " " + retval; } // if a hundreds part is there, translate it if (dig1>0)
retval = ones[dig1] + " hundred " + retval;

s=(s.Length - 3)>0 ? s.Substring(0,s.Length - 3) : "";
level++;
}

while (retval.IndexOf(" ")>0)
retval=retval.Replace(" "," ");

retval=retval.Trim();

if (isNegative)
retval="negative " + retval;

return (retval);
}


NOTE : You need to create .cs file. Include above code in it and then use Function wherever applicable in your application.

CSS Transparency Settings for All Browsers..

filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;


NOTE:
* opacity: 0.5; This is the “most important” one because it is the current standard in CSS. This will work in most versions of Firefox, Safari, and Opera. This would be all you need if all browsers supported current standards. Which, of course, they don’t.

* filter:alpha(opacity=50); This one you need for IE.

* -moz-opacity:0.5; You need this one to support way old school versions of the Mozilla browsers like Netscape Navigator.

* -khtml-opacity: 0.5; This is for way old versions of Safari (1.x) when the rendering engine it was using was still referred to as KTHML, as opposed to the current WebKit.

TO USE DIFFERENT STYLE.CSS FOR DIFFERENT BROWSER

<link href="style.css" type="text/css" rel="stylesheet" />

<!--[if IE 6]>

<link href="style_ie.css" type="text/css" rel="stylesheet" />
<![endif]-->


NOTE : Use Above code in your HEAD. Here style.css will be applied for all browser by default. But style_ie.css will be applied only to IE.

SENDING HTML MAIL IN ASP USING "CDONTS.NewMail"


<% dim html html = "Test Mail in ASP"
html = html & "Your HTML Body.."

Set Mail=Server.CreateObject("CDONTS.NewMail")
Mail.To="test@asp.com" 'Mail address to send.
Mail.From="test@asp.com" 'From Mail address.
Mail.Subject="Mail Test in ASP"
Mail.BodyFormat = 0
Mail.MailFormat = 0
Mail.Body=html
Mail.Send
Set Mail=nothing
%>


NOTE:Above is the code to send HTML mail in ASP. Variable html contains your html code which you need to send. Here in html variable you can write any html code, which you need to send in mail.

Sending mail in ASP using "CDO.Message"


<% Set myMail=CreateObject("CDO.Message") myMail.Subject="Sending email with CDO" myMail.From="mymail@mydomain.com" myMail.To="someone@somedomain.com" myMail.TextBody="This is a message." myMail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2 'Name or IP of remote SMTP server myMail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com" 'Server port myMail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 myMail.Configuration.Fields.Update myMail.Send set myMail=nothing %>

Gridview Paging


1) include this on your HTML page in Gridview Property:

<asp:GridView ID="gridView" AllowPaging="true" OnPageIndexChanging="gridView_PageIndexChanging" >

2) On .aspx.cs file include this method:

protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
gridView.DataBind();
}


NOTE: Page size & Page mode can be set from Gridview Property Window.