Send Email From ASP.NET site

Many times we want to send auto email to our website viewer or website owner. As we require after the viewer of website submits any enquiry then it should be come immediate in email Inbox Or In E-Commerce website after successfully purchasing any item a auto email notification will be send to customer (billing detail) and as well as website administrator also.
So that I use two variation of code for sending email as shown below. For this we require a email account and password for authentication.

First one is require your any one email account, password and mail server detail. The second one is for using gmail account.


using System.Web.Mail;
class abc
{
    public bool mailsend(string sSubject, string sBody, string sMailFrom, string sToMail, string sIsAdmin)
    {
        try
        {
            MailMessage sMail = new System.Web.Mail.MailMessage();
            sMail.To = sToMail.ToString();
            sMail.From = sMailFrom.ToString();
            sMail.Subject = sSubject.ToString();
            sMail.Body = sBody.ToString();
            sMail.Priority = MailPriority.High;
            sMail.BodyFormat = MailFormat.Html;
            SmtpMail.SmtpServer = "mail.website.com"// your mail server name
 
            sMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate""1");  //basic authentication
            sMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername""emailid");  //set your username here
            sMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword""password");  //set your password here
            SmtpMail.Send(sMail);
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
 
    // using by gmail id for authentication
    public bool mailsend(string to, string sub, string msg, string replyto)
    {
        string from = "yourmailid@gmail.com"//Replace this with your own correct Gmail Address
        string pwd = "password"// Replace this with your above email id password.
        bool status = false;
        System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage();
        email.To.Add(to);
        email.From = new System.Net.Mail.MailAddress(to, "Client", System.Text.Encoding.UTF8);
        string mailbody = msg;
        email.Subject = sub;
 
        email.ReplyTo = new System.Net.Mail.MailAddress(replyto, "", System.Text.Encoding.UTF8);
 
        email.SubjectEncoding = System.Text.Encoding.UTF8;
        email.Body = mailbody;
        email.BodyEncoding = System.Text.Encoding.UTF8;
        email.IsBodyHtml = true;
        System.Net.Mail.SmtpClient emailclient = new System.Net.Mail.SmtpClient();
        client.Credentials = new System.Net.NetworkCredential(from, pwd);
        client.Port = 587; // Gmail works on this port
        client.Host = "smtp.gmail.com";
        client.EnableSsl = true//Gmail works on Server Secured Layer
        try
        {
            emailclient.Send(email);
            status = true;
            return (status);
        }
        catch (Exception ex)
        {
            status = false;
            return (status);
        }
    }
}

Getting Started With C# - List of Best Sources

There has been a noticeable increase in people asking where to start C# recently. So I have been across a couple of forums and pulled together a list of some useful links and resources.

Web Tutorials

Helpful Tips

Useful Resources

MSDN resources:


10 C#.NET Features You May Not Know About - CSharp.NET

I thought it would be useful to document some of the typically lesser known features of the C# programming language and the .NET framework as a series of posts. Some of these features I've found useful and others I probably just haven't found a suitable use case for yet.

1. Anonymous Code Scopes in Methods

It's possible to have anonymous inner scopes within your method definitions. (I'm yet to come across a non-contrived use case for this!)

void MethodWithAnonymousScope()
    {
        var helloPart = "Hello";
        {
            var worldPart = "world";
            Console.WriteLine("{0} {1}", helloPart, worldPart);
        }
        // "worldPart" doesn't resolve in this scope
    }


2. Increment/Decrement Operator Position Significance

The position of the increment (++) and decrement (--) operators is significant. In the example below, when the increment operator is used as a postfix, it returns the value of 'number' before it has been incremented. Conversely, the prefix increment operator returns the value after it has been incremented. The decrement operator works with the same logic but decrements the number.

void PlusPlusOperator()
    {
        var number = 0;
        Console.WriteLine(number++); // Outputs zero
        Console.WriteLine(++number); // Outputs two
    }
 





3. The Default Keyword

The default keyword is a neat way to get the default value for a specified type. It's especially useful when working in a generic context.

void DefaultKeyword()
    {
        var intDefault = default(int); // default(int) == 0
        var boolDefault = default(bool); // default(bool) == false
        // default(string) == null (as for all reference types)
        var stringDefault = default(string);
    }




4. Null-Coalescing Operator

The null-coalescing operator (??) provides a succinct way of returning a default value if your reference or nullable-value type is null. In the following example, if myNullableInteger (left operand) is not null, then it's returned, else the default value for int is returned (right operand)


int NullCoalescingOperator()
    {
        int? myNullableInteger = SomeMethodThatCouldReturnNull();
        return myNullableInteger ?? default(int);
    }


5. Short-Circuit Evaluation with Boolean Operators

The logical AND (&&) and OR (||) operators are short-circuit evaluated (left to right). For example, if the left operand of a logical AND is false, the right operand is not evaluated (as the whole condition will always be false). Similarly, if the left operand of a logical OR is true, the right operand is not evaluated. This can be demonstrated by observing the output of

void ShortCircuitEvaluation()
{
    bool result;
    result = LeftOperand(true) || RightOperand(false);
    result = LeftOperand(false) || RightOperand(true);
    result = LeftOperand(true) && RightOperand(false);
    result = LeftOperand(false) && RightOperand(true);
}
bool LeftOperand(bool value)
{
    Console.WriteLine("Left operand evaluated");
    return value;
}
bool RightOperand(bool value)
{
    Console.WriteLine("Right operand evaluated");
    return value;
}


It's useful to know this so that you can safely perform multiple tests in a single if statement. In the example below, if myObject is null, the right operand is not evaluated (which is good because it'd cause a  NullReferenceException).

if (myObject != null && myObject.SomeProperty == SomeValue)
    ...
Also note that if you use a single '&' and single '|' you bypass short-circuit evaluation and force the entire condition to be evaluated.

6. Aliases for Generic Types

You can assign an alias to a namespace but you can also assign an alias to a specific generic type to save yourself from typing the awkward generic syntax over and over again (especially useful when working with key/value pair based generic types where the value may also be a key/value pair!).


using StringList = System.Collections.Generic.List<string>;
...
void GenericAliases()
{
    // Can use the alias "StringList"
    // instead of List<string>
 
    var stringList = new StringList();
    stringList.Add("Hello");
    stringList.Add("World");
    stringList.ForEach(Console.WriteLine);
} 


7. Extension Methods on Dynamic Types

I came across this one when working with the dynamic ViewBag in ASP.NET MVC. As the title states, you cannot invoke an extension method on a type (that has the extension method defined for it and is in scope) which is dynamically typed. I have documented this one in this post (click to view). As the post shows, you have to call your extension method in the same fashion as you would call a standard static method, then pass your dynamically typed variable in as a parameter to the extension method.

8. System.String supports an Indexer

The string class has a readonly (get) char indexer defined on it, thus allowing you to access characters in the string using a zero-based index.

void StringIndexer()
{
    string message = "Hello, world!";
 
    for (int i = 0; i < message.Length; i++)
    {
        Console.WriteLine(message[i]);
    }
}




9. Using foreach with System.String

The string class implements the IEnumerable<char> interface, which means that you can use the foreach statement on a string to enumerate through each character.

void ForeachWithString()
{
    string message = "Hello, world!";
 
    foreach (char character in message)
    {
        Console.WriteLine(character);
    }
}

10. Introspecting Code with Expression Trees

The System.Linq.Expressions.Expression class enables you to represent a code expression in a tree-based data structure that can then be used for introspection. This is a powerful feature which also then enables code modification in the expression tree (at runtime) and then subsequent compilation and execution.

The following example shows how we can wrap a simple lambda expression into an Expression, introspect the expression, compile the expression (in this case returning a Func<int, int, int>) and then execute the expression.

void Expressions()
{
    Expression<Func<intintint>> addExpression = (a, b) => a + b;
 
    foreach (var param in addExpression.Parameters)
    {
        Console.WriteLine(
            "Func Param Name: {0}, Param Type: {1}",
            param.Name,
            param.Type);
    }
 
    Console.WriteLine("Func return type: {0}",
        addExpression.ReturnType);
 
    Console.WriteLine("10 + 20 = {0}",
        addExpression.Compile()(10, 20));
 
    // Can also use the Invoke method on the returned Func<...>
    // to aid readability
    // e.g. addExpression.Compile().Invoke(10, 20);
}


You may have indirectly used expression trees if you're an ASP.NET MVC developer. The HTML helper classes make extensive use of them, for example, the Html.TextBoxFor method has an overload that accepts a single parameter of type Expression<Func<dynamic, dynamic>>. An example call to this method would be @Html.TextBoxFor(m => m.FirstName) where 'm' is an instance of your view model. The TextBoxFor method uses the supplied expression (a lambda) to construct the HTML that is put back into the view. In this case it outputs an input element with an id and name attribute value of "FirstName" - which was retrieved using introspection (made possible with expression trees).

Export GridView Data to Word - ASP.NET

Some time we need to generate different kind of reports & need to save it in Excel or word Document for Local Reference, Or sending to other's. So here I create a code for achieve this task the first one is conversion data into Excel & second one is for Word Document.

// For pdf converstion we can use third party dll like ITextSharp

using System; 
public class Class1
{
    protected void btn_word_Click(object sender, EventArgs e)
    {
        Response.AddHeader("content-disposition""attachment;filename=myreport.doc");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.word";
        System.IO.StringWriter swriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlwriter = new HtmlTextWriter(swriter);
 
        // Create a form to contain the gridview(MyGridView)
        HtmlForm mynewform = new HtmlForm();
        MyGridView.Parent.Controls.Add(mynewform);
        mynewform.Attributes["runat"] = "server";
        mynewform.Controls.Add(MyGridView);
        mynewform.RenderControl(htmlwriter);
        Response.Write(swriter.ToString());
        Response.End();
    }
}
 
 
Export GridView Data to Excel - ASP.NET 

Export Grid View Data To Excel - ASP.NET

Some time we need to generate different kind of reports & need to save it in Excel or word Document for Local Reference, Or sending to others. So here I create a code for achieve this task the first one is  conversion data into Excel & second one is for Word Document.

// For pdf converstion we can use third party dll like ITextSharp

 
using System; 
 
public class Class1
{    
    protected void btn_excel_Click(object sender, EventArgs e)
        {
            string attachment = "attachment; filename=myreport.xls";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/ms-excel";
            StringWriter swriter = new StringWriter();
            HtmlTextWriter htmlwriter = new HtmlTextWriter(swriter);
 
            // Create a form to contain the gridview(MyGridView)
            HtmlForm mynewform = new HtmlForm();
            MyGridView.Parent.Controls.Add(mynewform);
            mynewform.Attributes["runat"] = "server";
            mynewform.Controls.Add(MyGridView);
            mynewform.RenderControl(htmlwriter);
            Response.Write(swriter.ToString());
            Response.End();
        }    
}
 
 
Check out Export GridView Data to Word - ASP.NET 

Upload Image by external URL - ASP.NET

Sometime we need to upload image option using URL of image(from some external resources). So that we need not to download it and then upload in our website & also need not to use external image link in our website. This code create new image in your website folder(here i used yourfolder).

using System.Net;
using System.IO;
using System.Drawing;
 
public void saveimage(string imageURL)
{
    Stream imageStream = new WebClient().OpenRead(imageURL);
    System.Drawing.Image img = System.Drawing.Image.FromStream(imageStream);
    string path = Server.MapPath("yourfolder") + "\\test.jpg";
    img.Save(path);
}

Introducing DVLUP - A Program of Good Hope for Developers

DVLUP LOGO

Are you planning to publishing your first Windows Phone app? Or, give your existing App some well-deserved attention in Windows Phone Store ?
Wanna make some money out of your Windows Phone application but so far you have not earned a lot ?
Are you a fan of C# or .net Technologies ?

Let me introduce bad-ass program from Nokia just for you :-)

DVLUP helps developers become more successul Have fun. Earn Rewards. Build New Ideas.


By joining DVLUP, you’ll get exclusive access to App Challenges, news, events, partner opportunities and more. Earn points to redeem for Rewards, including promotional placements for your Apps. And if exclusive access and glory aren’t enough, we’ve got more badges than the lost & found at a police convention. 
( source DVLUP )

DVLUP Campaigns offers you merchandising, marketing, and advertising capabilities for your applications in key Lumia and Asha consumer channel.


WHAT IS IT ALL ABOUT?


DVLUP gives developers exclusive access to App Challenges, news, events, partner opportunities and more. Developers can earn points to redeem for Rewards, including promotional placements for their Apps.

DVLUP uses a gamification model to create a fun, inventive and competitive environment for developers to build successful Windows Phone applications. Developers can earn badges and experience points (known as “XP”) by completing quizzes and challenges related to application development. By creating high-quality applications, developers can also earn additional points and unlock even greater opportunities.

Originally, DVLUP was a comic book, and not called DVLUP. DVLUP began as a pilot program in the United States and Canada in November 2012, and today is available in more than 20 countries including Australia, Canada, China, Egypt, Finland, France, Germany, India, Indonesia, Italy, Kenya, Poland, United Kingdom, the United States and Vietnam, with more countries being added regularly.




HOW TO START?


Follow the following steps: 
  1. Register at Windows Dev Center.  ( Get free token by signing in here MadeWithMarmalade )
  2. Register Here : DVLUP
  3. Get start with Quiz and challenges
  4. Submit any good ideas and apps
  5. Earn as much XP(Points) as you can...

Lots of Nokia DVLUP backpack stuffed with goodies and prizes awaiting just FOR you! Just go and Prove your talent.

five million dollars. 

Yup nothing is wrong with your eyes here, nor I made any typing error.
That is the amount of money that Nokia is putting into the various rewards and app promotion opportunities available for DVLUP members around the world. 
Don't delay. Keep working on those Challenges, earning your XP, and claim your share of our $5 million reward pool. You will only have yourself to blame if you miss out.


Quick glance of DVLUP Challanges :

some of DVLUP Challenges


A quick glance of Rewards from DVLUP :

some of Rewards from DVLUP

Format date using Javascript

A Simple javascript function to format date. Pass a date as an argument and get formatted date.

I needed a JavaScript date format function such as the Visual Basic Format function, in which you can pass a format string and get the formatted string back; my first approach was to issue a series of consecutive and "destructive" replace calls, but upon discovering that the 5.5 (or higher) version of JScript supported the use of a function as the replaceTextargument of the replace method, I got creative.
Here's an example call of what I wanted:


SomeDiv.innerText = (new Date()).format('dddd, mmmm dd, yyyy.');

This would display:

Saturday, July 16, 2005


So in my first approach, I globally and case-insensitively replaced dddd with the corresponding string, which "destroyed" every occurrence, so that later in the code I could replace dd with the date number.

This worked just fine, but I knew that by inspecting the format specifier for a match, I could skip the search of every format specifier; say I only want the month and the date; well, by switching upon the format specifier (or rather "datepart" specifier), the year replacement will never be issued. Get it?

The fun part relies in the use of a function in the replaceText argument of the replace method; this way the $1 property as a function argument always represents the last match.

Other considerations include the format or "datepart" specifiers: none other than yyyy will be parsed as the year; months and days have the usual three flavors of fullname (mmmm), three-letter (mmm) or numeric (mm); hours (hh) can be rectified to the 12-hour format with the a/p specifier, and minutes (nn) and seconds (ss) may also be specified.

Javascript Function


// a global month names array
var gsMonthNames = new Array(
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
);
// a global day names array
var gsDayNames = new Array(
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
);
// the date format prototype
Date.prototype.format = function(f)
{
if (!this.valueOf())
return '&nbsp;';

var d = this;

return f.replace(/(yyyy|mmmm|mmm|mm|dddd|ddd|dd|hh|nn|ss|a\/p)/gi,
function($1)
{
switch ($1.toLowerCase())
{
case 'yyyy': return d.getFullYear();
case 'mmmm': return gsMonthNames[d.getMonth()];
case 'mmm': return gsMonthNames[d.getMonth()].substr(0, 3);
case 'mm': return (d.getMonth() + 1).zf(2);
case 'dddd': return gsDayNames[d.getDay()];
case 'ddd': return gsDayNames[d.getDay()].substr(0, 3);
case 'dd': return d.getDate().zf(2);
case 'hh': return ((h = d.getHours() % 12) ? h : 12).zf(2);
case 'nn': return d.getMinutes().zf(2);
case 'ss': return d.getSeconds().zf(2);
case 'a/p': return d.getHours() < 12 ? 'a' : 'p';
}
}
);
}

CSS Selectors with examples

This Article is about CSS selector and how it woks. Following is explanation of most of the selector that is used in CSS.

In the following first is css example and than html code on which it will work, so to try by yourself create html page and put the css as well as related Html and see the result. In most of the select I provided demo link where you can visit and see the result.

In below post you might find some new CSS selector that are the part of new CSS3. All of the below examples and demo tried by me on latest Chrome version.


.Class -: Select all the element with given class name

sample css :

Code Snippet
  1. .MyIntro
  2. {
  3.   font:15px arial,sans-serif;
  4.   color:red;
  5. }

sample html :

Code Snippet
  1. <div class="MyIntro">
  2.     <p>My name is Pranay Rana.</p>
  3.     <p>I am working as Soft Engg.</p>
  4. </div>


#id -: Select all the element with given id name

sample class :

Code Snippet
  1. #MyIntro {
  2.     font: 15px arial,sans-serif;
  3.     color: red;
  4. }

sample HTML :

Code Snippet
  1. <div id="MyIntro">
  2.     <p>My name is Pranay Rana.</p>
  3.     <p>I am working as Soft Engg.</p>
  4. </div>

Point to Note : You can have more than one element having same classname in HTML page but you can have only one element with the ID.


HTMLElement - Select all the html element which name is given.

Sample CSS :

Code Snippet
  1. p {
  2.     font: 15px arial,sans-serif;
  3.     color: red;
  4. }

Sample HTML :

Code Snippet
  1. <div>
  2.     <p>My name is Pranay Rana.</p>
  3.     <p>I am working as Soft Engg.</p>
  4. </div>


HtmlElement HtmlElemnt - Select all the html element which are in html element.

Sample CSS :

Code Snippet
  1. div p {
  2.     font: 15px arial,sans-serif;
  3.     color: red;
  4. }

Sample HTML :

Code Snippet
  1. <div>
  2.     <p>My name is Pranay Rana.</p>
  3.     <span>
  4.         <p>data </p>
  5.     </span>
  6. </div>
  7. <p>I am working as Soft Engg.</p>

in this example all p element inside div get highlighted with read color, but p element outside div doesnt get affected.


HtmlElement > HtmlElemnt - Select all the html element which are child of html element.

Sample CSS :

Code Snippet
  1. div > p {
  2.     font: 15px arial,sans-serif;
  3.     color: red;
  4. }

Sample HTML :

Code Snippet
  1. <div>
  2.     <p>My name is Pranay Rana.</p>
  3.     <span>
  4.         <p>data </p>
  5.     </span>
  6. </div>
  7. <p>I am working as Soft Engg.</p>

in this example all p element which are child of div get highlighted with read color, but p element which are not child of div doesnt get affected.


HtmlElement + HtmlElemnt - Select all the html element which are immediate after html element.

Sample CSS :

Code Snippet
  1. div + p {
  2.     font: 15px arial,sans-serif;
  3.     color: red;
  4. }

Sample HTML :

Code Snippet
  1. <div>
  2.     <p>My name is Pranay Rana.</p>
  3. </div>
  4. <p>I am working as Soft Engg.</p>
  5. <p>data </p>

in this example p element which is immediate after div get highlighted with read color, in this example "I am working as Soft Engg." this text get highlighted.


HtmlElement ~ HtmlElemnt - Select all the html element which are precedes html element.

Sample CSS :

Code Snippet
  1. div ~ p {
  2.     font: 15px arial,sans-serif;
  3.     color: red;
  4. }

Sample HTML :

Code Snippet
  1. <div>
  2.     <p>My name is Pranay Rana.</p>
  3.     <span>
  4.         <p>data </p>
  5.     </span>
  6. </div>
  7. <p>I am working as Soft Engg.</p>
  8. <p>My Demo Page.</p>

in this example p element which is precedes div get highlighted with read color, in this example "I am working as Soft Engg." and "My Demo Page." text get highlighted.


[attribute] - Select all the html element which is having attribute.

Sample CSS :

Code Snippet
  1. [data-name] {
  2.     font: 15px arial,sans-serif;
  3.     color: red;
  4. }

Sample HTML :

Code Snippet
  1. <div>
  2.     <p data-name="pranay">My name is Pranay Rana.</p>
  3.     <span>
  4.         <p>data </p>
  5.     </span>
  6. </div>
  7. <p>I am working as Soft Engg.</p>
  8. <p data-name="demo">My Demo Page.</p>

in this example any element which is having attribute "data-name"div get highlighted with red color, in this example "My name is Pranay Rana." and "My Demo Page." text get highlighted.


[attribute = data] - Select all the html element which is having attribute value equal to data.

Sample CSS :

Code Snippet
  1. [data-name = 'demo'] {
  2.     font: 15px arial,sans-serif;
  3.     color: red;
  4. }

Sample HTML :

Code Snippet
  1. <div>
  2.     <p data-name="pranay">My name is Pranay Rana.</p>
  3.     <span>
  4.         <p>data </p>
  5.     </span>
  6. </div>
  7. <p>I am working as Soft Engg.</p>
  8. <p data-name="demo">My Demo Page.</p>

in this example any element which is having attribute "data-name" and value = "demo" get highlighted with red color, in this example "My Demo Page." text get highlighted.


[attribute ^= data] - Select all the html element where attribute value begins with data.

Sample CSS :

Code Snippet
  1. [data-name ^= 'pra'] {
  2.     font: 15px arial,sans-serif;
  3.     color: red;
  4. }

So with the above html when apply this "My name is Pranjal Panchal." text is get highlighted because its "data-name" attribute value begining with "pra".


[attribute $= data] - Select all the html element where attribute value end with data.

Sample CSS :

Code Snippet
  1. [data-name ^= 'jal'] {
  2.     font: 15px arial,sans-serif;
  3.     color: red;
  4. }

So with the above html when apply this "My name is Pranjal Panchal." text is get highlighted because its "data-name" attribute value ending with "jal".


[attribute *= data] - Select all the html element where attribute value contains data.

Sample CSS :

Code Snippet
  1. [data-name *= 'panchal'] {
  2.     font: 15px arial,sans-serif;
  3.     color: red;
  4. }

So with the above html when apply this "My name is Pranjal Panchal." text is get highlighted because its "data-name" attribute value contains "pannchal".


[attribute ~= data] - Select all the html element where attribute value contains word data.

Sample CSS :

Code Snippet
  1. [data-name ~= 'page'] {
  2.     font: 15px arial,sans-serif;
  3.     color: red;
  4. }

Sample HTML :

Code Snippet
  1. <div>
  2.     <p data-name="pranay_page">My name is Pranay Rana.</p>
  3.     <span>
  4.         <p>data </p>
  5.     </span>
  6. </div>
  7. <p>I am working as Soft Engg.</p>
  8. <p data-name="demo page">My Demo Page.</p>

in this example any element where attribute "data-name" value contains word = "page" get highlighted with red color, in this example "My Demo Page." text get highlighted


:first-child - Select first element (first child) of parent.

Sample CSS :

Code Snippet
  1. li:first-child {
  2.     font: 15px arial,sans-serif;
  3.     color: red;
  4. }

Sample HTML :

Code Snippet
  1. <ul>
  2.     <li>item1</li>
  3.     <li>item2</li>
  4.     <li>item3</li>
  5.     <li>item4</li>
  6. </ul>

in this example "item1" element get highlighted with red color.


:last-child - Select last element (last child) of parent.

Sample CSS :

Code Snippet
  1. li:last-child {
  2.     font: 15px arial,sans-serif;
  3.     color: red;
  4. }

Sample HTML :

Code Snippet
  1. <ul>
  2.     <li>item1</li>
  3.     <li>item2</li>
  4.     <li>item3</li>
  5.     <li>item4</li>
  6. </ul>

in this example "item4" element get highlighted with red color.


:nth-child(n) - Select all each element which n the child of parent.

Sample CSS :

Code Snippet
  1. li:nth-child(2) {
  2.     font: 15px arial,sans-serif;
  3.     color: red;
  4. }

Sample HTML :

Code Snippet
  1. <ul>
  2.     <li>item1</li>
  3.     <li>item2</li>
  4.     <li>item3</li>
  5.     <li>item4</li>
  6. </ul>

in this example "second li" element get highlighted with red color, in this example "item2" text get highlighted.



:empty - Select element which is empty i.e. donent have any child.

Sample CSS :

div:empty
{
  width:100px;
height:20px;
background:red;
}

Sample HTML :

<div></div>
<div>
    <p> pragraph 2</p>
    <p> pragraph 3</p>
    <p> pragraph 4</p>
</div>

in this highlight all text in the document with red color.


::selection - highlight the text with the color selected.

Sample CSS :

::selection
{
  background:green;
}

Sample HTML :

<div> <p> pragraph 1</p> </div>
   <div>
    <p> pragraph 2</p>
    <p> pragraph 3</p>
    <p> pragraph 4</p>
</div>  

in this highlight all text with green which get select in document.


:not(HTMLElement) - it not apply the style to the HTMLElement specified.

Sample CSS :

:not(span)
{
  font:15px arial,sans-serif;
  color:red;
}
span
{
  color:black;
}

Sample HTML :

 <p> pragraph 1</p>
 <p> pragraph 2</p>
 <p> pragraph 3</p>
 <p> pragraph 4</p>
 <span> span data</span>  

in this highlight all text which is in p element i.e. not apply style to span element.


:enable - select to all enable element.

:disable - select to all disable element.

Sample CSS :

:input[type="text"]:enabled
{
background:green;
}
input[type="text"]:disabled
{
background:red;
}


Sample HTML :

Name: <input type="text" value="Pranay Rana" /><br>
Country: <input type="text" disabled="disabled" value="India" />  

here name is get highlighted with red color and country box is get highlighted with green.