Difference between String and StringBuffer/StringBuilder

Well, the most important difference between String and StringBuffer/StringBuilder in java is that String object is immutable whereas StringBuffer/StringBuilder objects are mutable.
By immutable, we mean that the value stored in the String object cannot be changed. Then the next question that comes to our mind is “If String is immutable then how am I able to change the contents of the object whenever I wish to?” . Well, to be precise it’s not the same String object that reflects the changes you do. Internally a new String object is created to do the changes.
So suppose you declare a String object:
String myString = “Hello”;
Next, you want to append “Guest” to the same String. What do you do?
myString = myString + ” Guest”;
When you print the contents of myString the output will be “Hello Guest”. Although we made use of the same object(myString), internally a new object was created in the process. So, if you were to do some string operation involving an append or trim or some other method call to modify your string object, you would really be creating those many new objects of class String.
Now isn’t that a performance issue?
Yes, it definitely is.
Then how do you make your string operations efficient?
By using StringBuffer or StringBuilder.
How would that help?
Well, since StringBuffer/StringBuilder objects are mutable, we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.
Finally, whats the difference between StringBuffer and StringBuilder?
StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isn’t thread safe).
So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.
Incase you do not know – Here’s how you use StringBuilder
A simple Example to demonstrate that String object is Immutable
Incase you still have any doubts regarding String or StringBuilder then do leave a comment. I’ll be more than eager to help you out.
Note: StringBuilder was introduced in Java 1.5 (so if you happen to use versions 1.4 or below you’ll have to use StringBuffer)

Interview tips you dare not miss

Interview is your first impression on your dream company after your resume. From clothes to conduct to language to information to skill – everything is important. Employers don’t just want a skilled person, they want a complete package of skills and soft skills. Questions may differ from industry to industry, but some dos and don’ts remain the same. Here are a few tips for your next interview:
Know yourself
Though more important for first timers, but even those who have worked for a few years tend to short sell themselves. Know your strong, weak and saleable points. Understand the job profile thoroughly and articulate your words accordingly.
Know the interviewer
In times of social networking and professional networking it’s very easy to know the person you are scheduled to meet. Try to look up the profile of the interviewer, it will help you conduct yourself in the right way.
Identify saleable points and talk well about them
You know your job and your achievements more than anyone. Be prepared and prioritise them in your head. Depending on the profile state nice and crisp without sounding verbose.
Do not keep personals on the table
This includes everything from - bag, wallet, mobile and also your elbows. In terms of body language, this is a complete no. Don’t rest yourself o the table and keep your bag near the chair you are sitting on.
Informal formality
That’s the style for an interview these days. You have to be proper, without being stiff.
Dress smart
Your dress up may not be the only thing, but it’s the first thing to be noticed. Wearing formals is safe and best. Stay away from T-Shirts and torn jeans. Comfort and cleanliness should be the motto.
Ladies, be minimal
We are asking you to dress smart and not provocative. Stay away from plunging neck lines or short skirts. Heavy duppattas and too much jewelry will also be difficult to handle and will distract both the parties.
If you don't know the answer accept it
It’s not necessary that everyone knows everything. Please do not cook up, if you don't know the answer say so. Don't jump to answer a question, take time to think.
Don't try to be a wisecrack
Sense of humour is great, but in an interview you will be judged for things which matter to the company. Be light hearted but don’t be frivolous. For phone interviews, don’t let sarcasm make way through your voice.
Everyone wants a positive person
This may sound like a cliche, but be good human being. Employers are looking for more than skills. Be smart, don't criticise and don't accept criticism, tackle it.
Learn from every interaction
Every job profile has its own requirements. Don’t be disheartened if you are not called for the next round. Review it in your mind and do your learning and move to the next one.
Liked these tips?
Add your own super tips for an interview and help others win

AjaxControlToolkit’ TabContainer control’ Javascript functions. In ASP.NET

In my previous two blogs we saw some javascript tricks to work with ASP.NET AJAX controls. The links to my previous blogs are
  • Calling validator controls from javascript.
  • Hide/Show validator callout control using javascript.
In this blog we will start with a common requirement for the tab container control i.e. setting focus to a tab using javascript and later at the end of this blog we will also see some important javascript functions available with ASP.NET AJAX Tab Container control.
One of the coolest controls in the ASP.NET AJAX is the TabContainer. Recently I had the requirement to show controls in tabs and also if there was any validation error in any of the tab I need to set focus on that tab as well. So if you also have the same requirement like you wanted to set focus to a particular tab of ASP.NET Ajax TabContainer control using javascript then read on. Below is the html code for the page having a tab container and some other asp.net controls like the validation control, validator callout etc.
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="AJAXControls" %>
<!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 runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <AJAXControls:TabContainer runat="server" ID="tabContainer">
            <AJAXControls:TabPanel ID="firstTab" HeaderText="First Tab" runat="server">
                <ContentTemplate>
                    <asp:Label ID="Label1" runat="server">You are in the First tab. <br /> Press the submit button to see the validation result.</asp:Label>
                </ContentTemplate>
            </AJAXControls:TabPanel>
            <AJAXControls:TabPanel ID="secondTab" HeaderText="Second Tab" runat="server">
                <ContentTemplate>
                    <label id="Label2" runat="server">Please select a value from the drop down: </label>
                    <!--ASP.NET Drop down control-->
                    <asp:DropDownList ID="status" runat="server" >
                        <asp:ListItem Selected="True" Text="Select" Value="0" />
                        <asp:ListItem Text="One" />
                        <asp:ListItem Text="Two" />
                        <asp:ListItem Text="Three" />
                    </asp:DropDownList>
                    <!--ASP.NET Required Field Validator to validate the drop down.-->
                    <asp:RequiredFieldValidator ID="statusValidator" runat="server" ErrorMessage="Please choose a value other than 'Select'" ControlToValidate="status" InitialValue="0" Visible="true" Display="None">
                    </asp:RequiredFieldValidator>
                    <AJAXControls:ValidatorCalloutExtender ID="statusValidator_ValidatorCalloutExtender"
                        runat="server" TargetControlID="statusValidator">                     </AJAXControls:ValidatorCalloutExtender>                   
                </ContentTemplate>
            </AJAXControls:TabPanel>
        </AJAXControls:TabContainer>
        <br />
        <asp:Button ID="submit" Text="Submit" OnClientClick="javascript:return ValidatePage();"
            runat="server" />
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
    </div>
    </form>
</body>
</html>
So in the above html code you can see we have an AjaxControlToolkit TabContainer control with two TabPanels having id as “firstTab” and “secondTab”. The first tab has a label control and the second tab has a dropdown control with a validation control attached to it and a ValidatorCalloutExtender control attached to the validation control. Also we have a submit button with “OnClientClick” event calling a javscript function called “ValidatePage”. Now the problem is whenever the submit button is pressed and if there is a validation error in the second tab the user is not informed of the same, reason being he is in the first tab and error has happened in the second tab. When the user manually clicks on the second tab he is able to see the error and if he doesn’t click the second tab the user is oblivious of the error. The solution to the problem is to set focus on the second tab whenever there is a validation error in the second tab. The javascript solution for the same is pasted below.
<script language="javascript" type="text/javascript">
function ValidatePage()
{
    // Getting the validation control using the new $get function.
    var valCntl = $get('<%=statusValidator.ClientID%>');
    if (valCntl != undefined && valCntl != null)
    {
        /*ValidatorValidate function executes the validation logic associated with the validation control. */
        ValidatorValidate(valCntl); 
    /*isvalid property is set to a boolean value by the ValidatorValidate based on whether the validation logic associated with the validation control was successful or not. */
        if (!valCntl.isvalid)
        {
        /*User defined method to hide the validator callout control.
            hideValidatorCallout(); */
        /*Retrieving the tab container control using new $get javascript function. */
            var tabContainer = $get('<%=tabContainer.ClientID%>');
            if (tabContainer != undefined && tabContainer != null)
            {
                tabContainer = tabContainer.control;
                tabContainer.set_activeTabIndex(1);
                showValidatorCallout();
            }
            return false;
        }
        return true;
    }
}
function hideValidatorCallout()
{    
    /*Below code hides the active AjaxControlToolkit ValidatorCalloutExtender control. */
    AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout.hide();
}
function showValidatorCallout()
{
    /*Gets the AjaxControlToolkit ValidatorCalloutExtender control using the $find method. */
    AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout = $find('<% =statusValidator_ValidatorCalloutExtender.ClientID %>');
    //Below code unhides the AjaxControlToolkit ValidatorCalloutExtender control.
    AjaxControlToolkit.ValidatorCalloutBehavior._currentCallout.show(true);
}
</script>
If you see in the above code we are calling ValidatePage javascript method on the button’ OnClientClick event. Inside the function we are making a call to the ValidatorValidate method with the validation control as the argument. Once that is done I am checking whether the validation logic associated with validation control has executed successfully or not by checking the isvalid property of the validation control. If the validation is not successful I am getting the tab container control using the “$get” javascript method. Once the tab container is retrieved the following two lines sets the focus to the desired tab.
tabContainer = tabContainer.control; 
tabContainer.set_activeTabIndex(1);
Once you retrieve the tab container object using the “control” property one can use “set_activeTabIndex” to set the focus to the required tab. The “set_activeTabIndex” method takes an integer (tab index) value as the argument. Using the “set_activeTabIndex” javascript method one can set focus to the required tab.
I have used a new javascript function called “$get” to retrieve an element. In my previous blog I have used “$find”, we will see the difference between these two in my next blog but for the time being just understand that “$get” is the short cut for “document.getElementById” javascript method.
Some other useful tab container control’ javascript functions
Below I have listed some of the important javscript functions which may be of use for developers like us. These methods can be used only after one has retrieved the ASP.NET AJAX TabContainer control using the following code “TABCONTAINER_CONTROL.control” as shown in the above codes.
Method Explanation
get_activeTab()
returns the current active tab javascript object i.e. the tab which is in focus. This javascript function gets the active tab object.
get_activeTabIndex()
gets the active tab index. The function returns an integer value of the active tab.
get_id() gets the id of the tab container control.
get_tabs() gets an array of all the tabs in a tab container control. The function returns a javascript array containing all the tabs in the tab container control.
get_visible()
returns a boolean value indicating whether the tab container is visible or not.
getFirstTab() gets the first tab in the tab container control. The function returns a tab having tab index 0.
getLastTab() gets the last tab in the tab container control. The function returns a tab object having tab index = (tab count) –1.
getNearestTab()
gets the nearest tab. If the current tab index is 0 then the method will return second tab i.e. the tab having tab index as 1 and if the tab index is greater than 0 the function will return the previous tab i.e. the tab having index = [Current Tab Index] – 1.
getNextTab()
gets the next tab in the tab container control i.e. if the current active tab is the last tab then the function will return the first tab as the next tab else it will return the next tab ([Current Tab Index] + 1)
getPreviousTab()
gets the previous tab in the tab container control i.e. if the current tab index is 0 then the function returns the last tab else it returns the previous tab ([Current Tab Index] - 1)
set_activeTab(tabControl)
sets the active tab. The function takes a tab object as its argument and sets the tab as the active tab.
set_activeTabIndex(integer)
functions takes an integer value starting from 0 to tab collection length – 1 as an argument and sets the tab’ index matching the integer value as the active tab.
set_id()
sets the id for the current tab container control.
set_visible(Boolean)
function takes a Boolean value and based on the value, hides or shows the tab container. The function/property makes the whole tab container control visible or invisible. To make individual tabs visible or invisible you need to work with the tabs property as shown in the below table.
Individual Tab object’ javascript functions
The above functions are related to the tab container control. There may situation where one might want to work with individual tab objects. To work with individual tabs one has to retrieve the individual tab by making us of any of the above tab retrieval functions from the table and then one can work with the individual tab. Sample e.g to retrieve individual tab is given below.
tabContainer = tabContainer.control;
//Retrieving the tab using the get_activeTab method/property
var tab = tabContainer.get_activeTab();
var headerText = tab.get_headerText();
alert(headerText);
//Another way of retrieving the tab using the get_previousTab method/property
tab = tabContainer.getPreviousTab();
alert(tab.get_tabIndex());
Once you have retrieved the individual tab using any of the above methods you can make use of some of the useful methods listed in the table below to work with the tab object. The methods listed in the below table are not the complete list but they are some of the methods which I feel may be useful for developers.
Methods Explanation
addCssClass(className) sets the CSS class. The function takes the CSS class name as the argument. You can make use of this javascript function to change the CSS class of a tab at runtime through javascript.
get_enabled()
gets a Boolean value indicating whether the tab is enabled or not (disabled). The function returns true or false.
get_headerText()
gets the header text of the tab. The function returns string containing the header text.
get_id() gets the id of the tab.
get_tabIndex() gets the tab index of the tab object. The function returns an integer.
get_visible() gets whether the tab is visible or not. The function returns a boolean value.
removeCssClass(className)
removes the CSS class based on the class name passed in the argument.
set_enabled(Boolean)
enables or disables the tab object based on the boolean value passed.
set_headerText(string)
function sets the header text for tab. Functions takes a string as an argument and sets the string as the header text.
set_id() sets the id for the tab.
set_visible(Boolean)
sets the visibility of the tab based on the boolean argument passed. The boolean value makes the tab visible or invisible.
In my next blog we will see the difference between $find and $get. Till then try to know more.

Tab Focus Event in ASP.NET

To make your Web application more efficient and easier to use, you need to remove any difficulty in web form navigation that your user could experience. User interface and web site navigation must be logical, easy to use and if possible: already well-known from other applications. Of course, nobody wants to learn some new complicated and unnecessary things and crawl through a large help files. Users wants self-explanatory interface that they can start to use immediately.


One of common standards is using a keyboard TAB key to move focus forward (or Tab + Shift key to move focus back) between controls on form, instead of forcing your Web site visitor to use a mouse click for changing a focus. Of course, your visitor still CAN use a mouse to set focus in some text box, but many of them, and they are usually experienced users like to use a tab key to move focus, because it is faster and more efficient way.

Tab order in web form

So, you need to define a logical navigation through a web form using a Tab key. There is a TabIndex property of server controls. First control in form should get lowest TabIndex. With every next tab, focus will move to the control with next higher value of TabIndex. It is pretty simple to set tab order, you need only to care about few common problems:
Problem 1: When we run the page, we can see there is no control with focus when web page is loaded. Much better solution is to have a focus on the right place immediately after page is loaded. Research about how you can set a focus initially and other focus issues you can see in Focus in ASP.NET tutorial. One solution, which shows how you can set a focus to textbox named txtFirstName, when page is loaded, could be a code like this:
 
[VB.NET]

Page.RegisterStartupScript("SetInitialFocus", _
"<script>document.getElementById('" & txtFirstName.ClientID & _
"').focus();</script>")

[C#]

Page.RegisterStartupScript("SetInitialFocus", "<script>document.getElementById('" + txtFirstName.ClientID + "').focus();</script>");
 

Problem 2: Focus moves through a web form, but also goes to Web browser address bar, Google or Yahoo toolbar etc. It is more expected that focus should move only inside the web form, instead to goes to browser's address bar.
Let say the last focus in on the button named "btnOK" and when user press tab key, we want to move focus again to the first control, textbox "txtFirstName" and skip focus in browser toolbars, address bars and other distraction things. You can do it with next piece of code:
 
[VB.NET]
btnOK.Attributes.Add("onkeydown", _
"if(event.which || event.keyCode)" & _
"{if ((event.which == 9) || (event.keyCode == 9)) " & _
"{document.getElementById('" & txtFirstName.ClientID & _
"').focus();return false;}} else {return true}; ")

[C#]

btnOK.Attributes.Add("onkeydown", "if(event.which || event.keyCode)" +
"{if ((event.which == 9) || (event.keyCode == 9)) " +
"{document.getElementById('"+ txtFirstName.ClientID +
"').focus();return false;}} else {return true}; ");
 

You don't want to move a focus to specific control?

For some reason, you don't want to some control receive a focus. That could be a case if, for example you have an invisible text box or some search text box on top of the web page, but you want to allow tab functionality only to few main controls on the web form. Simply set TabIndex property of server control, or tabindex attribute of HTML control to -1. When you run web page and hit tab key, controls with TabIndex = -1 will never get a focus. Although, user can click into this control with a mouse and set focus on that way.

Web form sample project of using TAB key

You can download sample "Contact form" Visual Studio 2003 or Visual Studio 2005 project which shows you how you can manage focus on page load and move the focus using the Tab key. The sample contains simple contact form. When you start web application, textbox named "txtFirstName" gets a focus when page is loaded. If you press Tab key, focus will move to the next control, depending of value of control's TabIndex property. When focus comes to the last control with the biggest TabIndex, it goes again to the first control, txtFirstName. There is also txtSearch textbox on the web form which never can be "tabbed" and can receive focus only with a mouse click in it.

How to type TAB key in textbox or textarea


Sometimes, you don't need to move cursor to the next control when hit Tab key. What if you need to type Tab character into text box or text area as a part of the text? Of course, your user can type tab in Notepad or some other text editor and simply do copy/paste to your form, but it is not so nice solution and users could say your application is not professional :). Instead of that, to type tab key in text box, you can use script like this (text box which accepts tab keys is named txtLongText):
 
[VB.NET]

txtLongText.Attributes.Add("onkeydown", _
"if(event.which || event.keyCode){if ((event.which == 9)" & _
"|| (event.keyCode == 9)) {document.getElementById('" & _
txtLongText.ClientID + "').selection = " & _
document.selection.createRange();" & _
txtLongText.ClientID & ".selection.text = " & _
" String.fromCharCode(9);return false;}} else {return true}; ")

[C#]

txtLongText.Attributes.Add("onkeydown",
"if(event.which || event.keyCode){if ((event.which == 9)" +
"|| (event.keyCode == 9)) {document.getElementById('"+
txtLongText.ClientID + "').selection = document.selection.createRange();" +
txtLongText.ClientID + ".selection.text = String.fromCharCode(9);return false;}} else {return true}; ");
 
Or better, to avoid hard coding, you can put this code to function named EnableTabType. Function has only one parameter, which specifies what is TextBox control where you need to enable typing of Tab characters.
 
[VB.NET]

Public Sub EnableTabType(tb As TextBox)
    tb.Attributes.Add("onkeydown", _
    "if(event.which || event.keyCode){if((event.which == 9)" & _
    "|| (event.keyCode == 9)) {document.getElementById('" & _
    tb.ClientID & "').selection=document.selection.createRange();" & _
    tb.ClientID & ".selection.text = " & _
    " String.fromCharCode(9);return false;}}else{return true};")
End Sub

[C#]

public void EnableTabType(TextBox tb)
{
    tb.Attributes.Add("onkeydown",
    "if(event.which || event.keyCode){if ((event.which == 9)" +
    "|| (event.keyCode == 9)) {document.getElementById('"+
    tb.ClientID + "').selection = document.selection.createRange();" +
    tb.ClientID + ".selection.text = String.fromCharCode(9);return false;}} else {return true}; ");
}
 

Tab key endnote

Default value of TextBox AutoPostBack property is false. If you set it to true and if text in TextBox control is changed, tab key will cause form to submit. After submitting, it is possible to lose a focus on current control, especially if you used javascript on page load to set focus initially. In that specific case, you can register client script dynamically when Page.IsPostBack value is true.
With Bean Software Shortcut Controls you can use TAB key as a keyboard shortcut to call ASP.NET server side code. Also, with these controls, you can manipulate different keyboard shortcuts like simple Enter, Tab or placing a focus in specific text box, or more complicated e.g. Ctrl + Shift + O or similar, just like shortcuts used in Visual Studio or Microsoft Word. Source code is included.

Send Bulk Emails using C# VB.NET in ASP.NET

have been asked zillion times that How to Send Bulk Emails using C# or VB.NET in ASP.NET.

Well, there are hundreds of tutorials all over the internet on sending bulk emails in ASP.NET using C# or VB.NET.

However, I decided to post a basic "how to" for beginners so that they can easily understand the functionality of send bulk emails in ASP.NET.

For this example I will be using Northwind Database.

Step 1:





ASPX Code:

<form id="form1" runat="server">
    <div>
        Recipient(s):<br />
    <asp:TextBox ID="txtRecipient" runat="server" Height="50px" Width="525px"
            TextMode="MultiLine"></asp:TextBox>
        <br />
        <asp:Button ID="btnRecipientFromDB" runat="server"
            onclick="btnRecipientFromDB_Click" Text="Recipient From Database" />
        <br />
        <asp:CheckBoxList ID="chklstRecipientsFromDB" runat="server" Visible="False">
        </asp:CheckBoxList><asp:Button ID="btnAddSelected" runat="server"
            Text="Add Selected" onclick="btnAddSelected_Click" Visible="False" />
       
        <br />
        Subject:<br />
    <asp:TextBox ID="txtSubject" runat="server" Height="18px" Width="522px"></asp:TextBox>
   
        <br />
        <br />
        Email Body:<br />
        <asp:TextBox ID="txtEmailBody" runat="server" Height="290px" Width="520px"
            TextMode="MultiLine"></asp:TextBox>
        <br />
        <asp:Button ID="btnSend" runat="server" onclick="btnSend_Click"
            Text="Send Email" />
   
    </div>
</form>


This is simple form containing 3 TextBoxes

  1. Recipient(s)
  2. Email Subject
  3. Email Body
"Add Recipients from Database" button will show list of already added contacts from database as shown in image below:

Now, user has two options, either they can select multiple users from list and/or they can add recipients email address manually separated by ";"

Code Behind:
C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Net.Mail;

namespace TestApplication
{
    public partial class BulkEmail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                chklstRecipientsFromDB.Visible = false;
                btnAddSelected.Visible = false;
            }
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                #region Direct Email to db Recipients
                //if you want to send emails directly to recipient from database, use code below
                //DataSet dsClients = GetClientDataSet();
                //if (dsClients.Tables["Users"].Rows.Count > 0)
                //{
                //    foreach (DataRow dr in dsClients.Tables["Users"].Rows)
                //    {
                //        SendEmail(dr["Email"].ToString());
                //    }
                //}
                #endregion

                char[] splitter = { ';' };
                foreach (string emailAdd in txtRecipient.Text.Split(splitter))
                {
                    SendEmail(emailAdd);
                }
            }
            catch (Exception ex)
            {
            }
        }

        protected void btnRecipientFromDB_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet dsClients = GetClientDataSet();

                chklstRecipientsFromDB.DataSource = dsClients.Tables[0];
                chklstRecipientsFromDB.DataTextField = "Email";
                chklstRecipientsFromDB.DataValueField = "Email";
                chklstRecipientsFromDB.DataBind();

                chklstRecipientsFromDB.Visible = true;
                btnAddSelected.Visible = true;
                btnRecipientFromDB.Visible = false;
            }
            catch (Exception ex)
            {
            }
            finally
            {
            }
        }
        ///
        ///  Creates and returns a DataSet using Ms Access OleDBConnection and an OleDBDataAdapter
        ///
        ///
        /// A DataSet from Ms Access using an OleDBConnection and an OleDBDataAdapter
        ///
        private System.Data.DataSet GetClientDataSet()
        {

            //retrieve the connection string from the ConnectionString Key in Web.Config
            //string connectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
            string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Talha\Documents\Database2.accdb;Persist Security Info=False;";

            //create a new OleDB connection
            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connectionString);

            //pass the Select statement and connection information to the initializxation constructor for the OleDBDataAdapter
            System.Data.OleDb.OleDbDataAdapter myDataAdapter = new System.Data.OleDb.OleDbDataAdapter("SELECT Email FROM Employees", conn);

            //Create a new dataset with a table : CLIENTS
            System.Data.DataSet myDataSet = new System.Data.DataSet("Users");

            //Fill the dataset and table with the data retrieved by the select command
            myDataAdapter.Fill(myDataSet, "Users");

            //return the new dataset created
            return myDataSet;
        }
        private void SendEmail(string EmailAddress)
        {
            //Send Email Functionality here
            MailMessage mail = new MailMessage();
            mail.To.Add(EmailAddress);
            mail.From = new MailAddress("admin@codeshode.com");
            mail.Subject = txtSubject.Text;
            mail.Body = txtEmailBody.Text;

            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
            smtp.Credentials = new System.Net.NetworkCredential("YourUserName@gmail.com", "YourGmailPassword");//Or your Smtp Email ID and Password
            smtp.EnableSsl = true;
            smtp.Send(mail);
        }

        protected void btnAddSelected_Click(object sender, EventArgs e)
        {
            StringBuilder strRecipientEmails = new StringBuilder();
            foreach (ListItem chk in chklstRecipientsFromDB.Items)
            {
                if (chk.Selected)
                {
                    strRecipientEmails.Append(chk.Value);
                    strRecipientEmails.Append(";");
                }
            }
            txtRecipient.Text = strRecipientEmails.ToString();
            chklstRecipientsFromDB.Visible = false;
            btnAddSelected.Visible = false;
        }
    }
}


VB.NET:

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Text
Imports System.Net.Mail

Partial Public Class BulkEmail
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        If Not IsPostBack Then
            chklstRecipientsFromDB.Visible = False
            btnAddSelected.Visible = False
        End If
    End Sub

    Protected Sub btnSend_Click(sender As Object, e As EventArgs)
        Try
            '#Region "Direct Email to db Recipients"
            'if you want to send emails directly to recipient from database, use code below
            'DataSet dsClients = GetClientDataSet();
            'if (dsClients.Tables["Users"].Rows.Count > 0)
            '{
            '    foreach (DataRow dr in dsClients.Tables["Users"].Rows)
            '    {
            '        SendEmail(dr["Email"].ToString());
            '    }
            '}
            '#End Region

            Dim splitter As Char() = {";"c}
            For Each emailAdd As String In txtRecipient.Text.Split(splitter)
                SendEmail(emailAdd)
            Next
        Catch ex As Exception
        End Try
    End Sub

    Protected Sub btnRecipientFromDB_Click(sender As Object, e As EventArgs)
        Try
            Dim dsClients As DataSet = GetClientDataSet()

            chklstRecipientsFromDB.DataSource = dsClients.Tables(0)
            chklstRecipientsFromDB.DataTextField = "Email"
            chklstRecipientsFromDB.DataValueField = "Email"
            chklstRecipientsFromDB.DataBind()

            chklstRecipientsFromDB.Visible = True
            btnAddSelected.Visible = True
        Catch ex As Exception
        Finally
        End Try
    End Sub
    '''
    '''  Creates and returns a DataSet using Ms Access OleDBConnection and an OleDBDataAdapter
    '''
    '''
    ''' A DataSet from Ms Access using an OleDBConnection and an OleDBDataAdapter
    '''
    Private Function GetClientDataSet() As System.Data.DataSet

        'retrieve the connection string from the ConnectionString Key in Web.Config
        'string connectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
        Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Talha\Documents\Database2.accdb;Persist Security Info=False;"

        'create a new OleDB connection
        Dim conn As New System.Data.OleDb.OleDbConnection(connectionString)

        'pass the Select statement and connection information to the initializxation constructor for the OleDBDataAdapter
        Dim myDataAdapter As New System.Data.OleDb.OleDbDataAdapter("SELECT Email FROM Employees", conn)

        'Create a new dataset with a table : CLIENTS
        Dim myDataSet As New System.Data.DataSet("Users")

        'Fill the dataset and table with the data retrieved by the select command
        myDataAdapter.Fill(myDataSet, "Users")

        'return the new dataset created
        Return myDataSet
    End Function
    Private Sub SendEmail(EmailAddress As String)
        'Send Email Functionality here
        Dim mail As New MailMessage()
        mail.[To].Add(EmailAddress)
        mail.From = New MailAddress("admin@codeshode.com")
        mail.Subject = txtSubject.Text
        mail.Body = txtEmailBody.Text

        mail.IsBodyHtml = True
        Dim smtp As New SmtpClient()
        smtp.Host = "smtp.gmail.com"
        'Or Your SMTP Server Address
        smtp.Credentials = New System.Net.NetworkCredential("YourUserName@gmail.com", "YourGmailPassword")
        'Or your Smtp Email ID and Password
        smtp.EnableSsl = True
        smtp.Send(mail)
    End Sub

    Protected Sub btnAddSelected_Click(sender As Object, e As EventArgs)
        Dim strRecipientEmails As New StringBuilder()
        For Each chk As ListItem In chklstRecipientsFromDB.Items
            If chk.Selected Then
                strRecipientEmails.Append(chk.Value)
                strRecipientEmails.Append(";")
            End If
        Next
        txtRecipient.Text = strRecipientEmails.ToString()
        chklstRecipientsFromDB.Visible = False
        btnAddSelected.Visible = False
    End Sub
End Class



Now you may type Email Subject, Email Body and press "Send Email" to send bulk emails!


Thats It!!

Was that so difficult??

I dont think so.
However, for any query, feel free to contact me!

Happy Coding!
Happy Shoding!