Thursday, December 31, 2009

Happy New Year 2010!

Nepal: Country of rich culture

Hey World, Happy New Year 2010!

Enjoy your holidays. Forget all the odds of 2009 and plan meaningful life for 2010!

Wherever you spend your holidays this year-end, enjoy it with all your heart. And please accept my warm invitation to spend your holidays of New Year 2011 in Nepal – a world of its own! We are celebrating 2011 as Nepal Tourism Year – 2011. My kind request to add this year into your calendar so that your won’t miss what this mysterious country has to offer you – from Natural beauty to the Mt. Everest, from Hindu’s holy Pashupatinath to Buddhist’s holy Lumbini- the birth place of Lord Buddha, from the miraculous flora and fauna to the diversity of social and cultural property!

Nepal: Country of Mountains

Source of photos: Nepal Gallery

Many many happy returns! Happy new year 2010!

Friday, December 18, 2009

Toggle image using jquery for animated hide show in asp-net

Web masters find it attractive to mark or indicate some text in a page as special part. For example a featured product in a shopping cart would hold a finished featured icon image at its side. Similarly we see New image icon blinking at the side of some product or text. It is sometimes better by far to use such animated images to draw user's attention. How would you do this using jquery? The simple answer is that- toggle the image based on its display status, in a regular interval.

There exists a simple method in jquery plugin that accomplished this task:


Let's look at the simple example.

<td>This is some test news.</td>
<td style="height:45px"><img id="newImage" src="../images/new.jpg"
alt="New!" height="40px" width="40px"/></td>

<script type="text/javascript">

function imageFlickr()


In the page, I have added an image in a column of a table. Please use your own image (perhaps some 'New' image, as in the image above). Note the javascript setInterval() method that calls the function imageFlickr() every 300ms. In the method, we have the line:


The $(selector).toggle(interval) method toggles the show/hide property of the element. In the code, I haven't used the interval argument of toggle method. The interval in milliseconds defines the fade-in or fade-out speed of the element. Try this once and you will see great effect:


You are warmly welcome to share your experiences. You can start discussion by adding comments from the form below. You can help spreading out the words by bookmarking this article to
any of your favourite bookmarking site!

Happy Programming!

kick it on

Wednesday, December 2, 2009

Prevent page postback on enter key press in textbox in asp-net web page

In an web page, you may have experienced that pressing enter key postbacks the page. For example, take the following scenario:




<td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>




<td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>



<td colspan="2">

<asp:Button ID="btnOK" runat="server" Text="OK" />




In the page, if you press enter key in any of the textboxes, the page will postback, which is not desired.

1.0 What’s the reason?
Lets look at the html markup generated for the page:

The button control has been rendered with “submit” type, which is the reason of page postback when enter key is pressed in any of the textboxes. Note the following line in the image above:

<input id="btnOK" type="submit" value="OK" name="btnOK"/>

2.0 The Way Out
We can use two different approaches to prevent postback on enter key-press in any of the textboxes:

1. Using UseSubmitBehavior="false" in the button control’s markup
We can set UseSubmitBehavior="false" in the button markup:




<td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>




<td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>



<td colspan="2">

<asp:Button ID="btnOK" runat="server" Text="OK" UseSubmitBehavior="false" />




This stops rendering the button as type=”submit”. Now the rendered markup for the button will be:

Not the following line in the image above as captured from firebug:

<input id="btnOK" type="button" onclick="javascript:__doPostBack('btnOK','')" value="OK" name="btnOK"/>
This shows that there is no more type="submit" attribute, rather onclick="javascript:__doPostBack('btnOK','') has been added.

So you have successfully stopped the page postback now!

2. Prevent enter key press in all the textboxes
One another way to stop the page postback is to prevent enter key press in any of the textboxes. We can use jquery to easily perform the task. This way:

<script type="text/javascript">


$(':text').bind('keydown',function(e){ //on keydown for all textboxes

if(e.keyCode==13) //if this is enter key





On page load, all the textboxes in the form are bound to the keydown event to a function. In the function we check if the key pressed in the ‘enter key’. If so, we prevent the further bubbling of the event. Hence it prevents the page postback.

Note: You will need to reference the latest jquery file in the page to use the second technique.

3.0 Conclusion
We looked at two ways to prevent page postback on enter-key press in a textbox in web page. Both the techniques work well. But I would prefer the first one since this would save the extra client side manipulations in the user’s machine.

4.0 Looking towards hearing from you!
You are warmly welcome to share your experiences. You can start discussion by adding comments from the form below. You can help spreading out the words by bookmarking this article to any of your favourite bookmarking site!

Happy Programming!

kick it on

Wednesday, October 28, 2009

jQuery Mutually exclusive checkboxes in

We often see radio buttons to implement single choices out of many in web forms. Wouldn’t it be better if we could imply ‘choose one option from many’ using checkboxes? I have implemented such mutually exclusive checkboxes in using jquery. This certainly is not any new practice. We have already seen such mutually exclusive checkboxes in ajax, and perhaps there are others also. But achieving this functionality using a lightweight javascript library like jquery would be a benefit. So let’s start the race.

First of all, let me present the design philosophy of this realization of mutually exclusive checkboxes.

1. We will have a group of checkboxes with same css class name. We will not need the id of checkboxes besides for associating label to display text and make label clickable.

2. For our example, initially we will check one of the checkboxes. You may wish not to and this will work.

3. We can add any number of such groups of checkboxes but each group will have distinct class name. For example, one group of checkboxes can have class name ‘class1’ and other can have ‘class2’ and so on.

4. When a checkbox is checked, if it is already checked nothing will happen, otherwise this checkbox will be checked and all other checkboxes having the same class name as of this checked one will be unchecked.

5. If a checkbox is unchecked, we re-check it, since we want at least one checkbox checked. We can let a checkbox get unchecked if our requirement does not demand at least one option checked, but for this tutorial we will not let so.

By this time we have realized the need and design philosophy of implementing mutually exclusive checkboxes in using jquery. Now let’s proceed on.

We need the latest version of jquery which is available here [latest version is jquery 1.3.2 till date].

Fig:1 jQuery library added in website project

Now reference the jquery library file in the head section of the design page.

Fig:2 jQuery libray referenced in the header section of design page

Here goes the design markup code in the aspx page.

<form id="form1" runat="server">
<asp:Label ID="lblResult" runat="server" ForeColor="Green"></asp:Label>
<div id="toggleContainer">
I like to mix
<input type="checkbox" id="aspnet" class="firstClass" checked="checked" runat="server"/>
<label for="aspnet"></label>
<input type="checkbox" id="php" class="firstClass" runat="server"/>
<label for="php">php</label>
<input type="checkbox" id="jsp" class="firstClass" runat="server"/>
<label for="jsp">jsp</label>
<input type="checkbox" id="asp" class="firstClass" runat="server"/>
<label for="asp">asp</label>
<br /><br /> with
<input type="checkbox" id="jquery" class="secondClass" checked="checked" runat="server"/>
<label for="jquery">jquery</label>
<input type="checkbox" id="javascript" class="secondClass" runat="server"/>
<label for="javascript">pure javascript</label>
<input type="checkbox" id="aspnetajax" class="secondClass" runat="server"/>
<label for="aspnetajax"> ajax</label>
<input type="checkbox" id="thirdajax" class="secondClass" runat="server">
<label for="thirdajax">third party ajax</label>
<br /><br />
<asp:Button ID="btnResult" runat="server" OnClick="btnResult_Click" Text="Show Result!" />

Fig:3 Mutually exclusive checkboxes at initial state

As shown in the page code above, we have three different groups of checkboxes having class names firstClass and secondClass. Each group has one checkbox checked initially.

Now is the time to use and understand the jquery script in the page. Here is the complete code in the script block.

<script type="text/javascript">
//toggle all checkboxes in toggleContainer div
$('#toggleContainer :checkbox').bind('change',function(){
var thisClass=$(this).attr('class');
$('#toggleContainer :checkbox.'+thisClass+":not(#"")").removeAttr('checked');

Explanation of jquery code snippet

1. We put all the codes that are required to run at the page load within document’s ready event handler code block, so the first line.

2. toggleContainer is the div element we put all our checkboxes. We have done this to avoid collision with other checkboxes in the page. For all checkboxes [as by :checkbox selector] within this div element we bind change event. So, the following code block will execute when any checkbox is checked or unchecked.

3. In the change event, we read the class name of the current checkbox in thisClass variable. Note that we are reading the value of attribute class [as by .attr method, used to get or set value of an attribute]

4. If this checkbox has attribute ‘checked’, this means we are checking this checkbox exclusive of others in its group. So we uncheck all checkboxes other than itself having class name of this checkbox [stored in variable thisClass]. How we achieve this- uncheck all checkboxes other than this? Answer is: using : not[itself] selector. This selector excludes the matching dom element from the result.

5. If this class has no ‘checked’ attribute, this means the previously checked chexbox has been tried to uncheck which we prevent by re-checking this checkbox since this violates our design philosophy.

That’s all.

Reading Result

Remember the Show Result button in the pages? Yeah, we will publish the result as of user’s selections. Here goes the code-behind code snippet.

//prints your choices in the result label
protected void btnResult_Click(object sender, EventArgs e)
string result = "Oh, you like to mix ";
if (asp.Checked)
result += "asp";
else if (aspnet.Checked)
result += "";
else if (php.Checked)
result += "php";
result += "jsp";

result += "
with ";

if (jquery.Checked)
result += "jquery ajax!";
else if (javascript.Checked)
result += "pure javascript ajax!";
else if (aspnetajax.Checked)
result += " ajax!";
result += "other third party ajax!";

result += "

lblResult.Text = result;

Fig:4 Mutually exclusive checkboxes in action


In this simple yet descriptive tutorial we implemented mutually exclusive checkboxes in using latest javascript jquery library. Since we used class property of checkboxes, we have been able to implement this with any number of distinct groups of checkboxes. If you enjoyed this tutorial, please spread the words: bookmark this, share your opinions via comments or email this article etcetera! Happy programming!

kick it on

Thursday, September 3, 2009

Programming foa and fop to generate pdf files from xml and xslt

In real world, there is a great deal of demand of pdf files. Programmers often need to generate pdf file from data fed in different formats. One popular format is xml. There exists lots of ways to generate pdf files in different programming languages. And interestingly most of them are platform and program independent. Sweet!

I am currently programming xslt. There has been an interesting task. We have xml file as input and fop batch file which can be run to accept some xml, xslt and pdf files to generate pdf out of the xml and xslt file. With this scenario, all we have to do is write the xslt that styles and maps to the original xml file, which can be then rendered as pdf files.

We are writing xslt using foa. The fop can take this xslt as input. The foa even provides IDE to write xslt. And this free yet significant tool is very programmer-friendly in the sense it provides environment to integrate style and xml at once into the xslt from one place.

This is my first time with fop and foa. They do make great marriage. But there doesn't seem to be updates in foa since long time. The latest foa we get is too old to match the latest version of fop. How would this foa keep with the latest, new, improved fop?

Anyway, I hope to come up with more issues in using xsl. Keep up warming your programming. Happy programming!

Wednesday, August 12, 2009

International Youth Day 2009

Hi all. Today is August 12, 2009, the International Youth Day. May this day empower the youth all over the world!

Monday, August 10, 2009

Smart sorting, paging in asp-net, especially repeater control

Hi all. There has been little lagging in my presence to you all with new post. Actually these days there are lots of things in my mind. I am looking over the web to know the best performance practices. But most of the times I do get stuck with the same old strategies you can find everywhere if you search with the keyword – " performance tips" or so. However, these tips work 90% of the cases, they are intermediate ones. What about the advanced ones? There are some genius guys who have presented advanced and deep performance improvement techniques, and thanks to them. Good things cannot hide, so you are sure to find them over the web hanging here and there, no problem.

But here I am going to talk about one thing- paging and sorting in From the very beginning I am dissatisfied with the old, easy paging of gridview that really kills the spirit of web- faster response and scalability. In fact gridview and datagrid both generate heavy markup. The only good way to get rid of all these is to do custom paging, sorting with the gridview and datalist.

Then what about repeater control? Yes, the best option to go is use repeater and use custom sorting/paging with it. Repeater control has always won the heart of programmers- light, efficient and thus effective! I have just been through this better way of paging and sorting with gridview control. They have managed an example page also. I hope following the same pattern would make a good impression with repeater control also. We would certainly go different pattern for sorting- perhaps a dropdownlist populating all the column names and another dropdownlist with "asc" and "desc" for sorting direction.

As alternatives, I have also liked: this one from codeproject and this one discussed in tutorial.

What you think? I am still looking for the best paging in for gridview, datalist or repeater. Your suggestions and referrals are welcome. Please keep in mind that I am fond of performance friendly options. Thank you. Happy Programming!

kick it on

Friday, July 3, 2009

How to change second textbox text when the first textbox date of AJAX CalendarExtender changes?

Sometime ago I saw an interesting question in forum. It raised my enthusiasm. I started to code the requirement. And I found one. Here goes the requirement:


I have two text boxes inside my aspx page: a) the "txt1" and b) the "txt2". Both text boxes have CalendarExtender controls attached:
a) the txt1 has the "CalendarExtender1"
b) the txt2 has the"CalendarExtender2".

All I want is this:
Using client-side script (or other method without postbacks), I want when the user chooses a date from CalendarExtender1, the same date plus a day front to go to the txt2.

For example:
If the user chooses 03/28/2009 in the CalendarExtender1, I want the value of the txt2 to be the 03/29/2009....
Also, if the month reaches the end, I want the txt2 to take the new moth.

For example:
If the user chooses 03/31/2009 in the CalendarExtender1, I want the value of the txt2 to be the 04/01/2009....

That behavior I want to exists only to the CalendarExtender1 like I describe it. I don't want the user to be able to do this with CalendarExtender2 (the CalendarExtender2 has the default behavior)...

How can I accomplish that? Thank you very much!

There are two solutions provided to this requirement. Let me put them here.

Solution1: (By Kinjalin)

Here you have to add it in Javascript.

<cc1:CalendarExtender ID="ClExFromDt"                     runat="server"                     TargetControlID="TxtFromDate"                     PopupButtonID="BtnFromCal"                     Format="dd/MM/yyyy"                     OnClientDateSelectionChanged="AddDate"                     CssClass="calExt_Theme1"></cc1:CalendarExtender>

Here on OnBlur, write a Javascript function addDate

on Page_Load write the line " Text1.Attributes.Add("onblur", "javascript:addDate();")

& in Javascript Fetch the Value using document.getElementByID("TextBox1").value

add it using below Javascript & bit of ur Logic

//create the date
var myDate = new Date();

//add a day to the date
myDate.setDate(myDate.getDate() + 1);

//add a week
myDate.setDate(myDate.getDate() + 7);

After adding Show it in your TextBox2

$get(TextBox2).value = myDate

Thats it.

Solution2: (By sangam100)

Hi MinimalTech ,

Here goes the prototype, which is close to what kinjalin posted:

Add this script in the design page:


function addDays() {

dateParts = document.getElementById('txtDate1').value.split('/');

year = dateParts[2];

month = parseInt(dateParts[0])-1;

day = parseInt(dateParts[1]) + 1;

newDate = new Date ( year, month, day );

year = newDate.getYear();

month = newDate.getMonth()+1;

day = newDate.getDate();

formattedDate = month + '/' + day + '/' + year;




Now in the design page:

Date1:<asp:TextBox ID="txtDate1" runat="server"></asp:TextBox>  Date2 (One day forward):<asp:TextBox ID="txtDate2" runat="server"></asp:TextBox><cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate1" PopupButtonID="txtDate1"></cc1:CalendarExtender>

In the code behind.

txtDate1.Attributes.Add("onchange", "addDays();");

Now this works.

Hope this will be useful to all. Happy Programming!

Friday, June 26, 2009

Convert date to different date string using Convert function of ms sql server 2005

Many times we need to convert datetime to different strings representing date, varying from 2009/06/2009 to June 26, 2009, and so on. Microsoft sql server 2005 can do the job for us! I had the same need some time ago, and sql server did this for me. (By the way, don't we programmers often find it irritating to have datetime representations different in different data base providers and different programming languages? Yes. Exactly here is what I am pointing towards what sql server 2005 can do for us. Follow the rest of this article for the magic!)

This is the syntax:

CONVERT (data-type, date-time-string-input, date-display-style)

data-type: Any data type from nchar, nvarchar, char, varchar, binary, varbinary [length is optional, e.g. varchar(20) or varchar(22)
date-time-string-input: Date time string supplied as input (You can use GETDATE() function etc.)
date-display-style: The string style (You need '2009.06.26' or 'June 26, 2009' etc. You can even use the useful style number. Read on.)

Note: If you provide insufficient length, you may be trimming your result!

Now, here is a list of the sql query and the result to the query that will introduce a number of the ways to get desired date strings.

Result: Jun 26 2009 5:53PM

Result: 06/26/2009

Result: 2009.06.26

Result: 26/06/2009

Result: 26.06.2009

Result: 26-06-2009

Result: 26 Jun 2009

Result: Jun 26, 2009

Result: 17:49:42

Result: Jun 26 2009 5:50:02

Result: 06-26-2009

Result: 2009/06/26

Result: 26 Jun 2009 17:51:24

Result: 17:51:44:397

Result: 2009-06-26 18:00:17

Result: 2009-06-26 18:01:14

Result: 2009-06-26T18:02:00

As you can see, I have used the select statement to retrieve the desired sql query result. You can use it with any combination of sql query to perform any of the CRUD (Create, Read, Update and Delete) operations.

You can comment to add to the above list. It may be incomplete. Remember your participation is very important to make it more complete and more useful. You are as always heartily welcome to post you suggestions, comments, rate this article or spread the words by adding it to the social bookmarks! Happy Programming!

Shout it pimp it

Wednesday, June 10, 2009

Highlight gridview row on mouse over in asp net web page: Adding effects to the gridview control

Programmers heavily use the gridview control. Adding some effects to the gridview will change the appearance so that user interactivity increases. One of such effects is highlighting the gridview row on mouseover. With this short background let's go for the design markup of the example gridview.

<asp:GridView ID="gridTest" runat="server" OnRowDataBound="gridTest_RowDataBound" AutoGenerateColumns="false">


<asp:BoundField HeaderText="Status" DataField="Status" />

<asp:BoundField HeaderText="Name" DataField="Name" />

<asp:BoundField HeaderText="Comment" DataField="Comment" />

<asp:BoundField HeaderText="Date" DataField="Date" />



Now we have the gridview, why not choose the highlighted row's color? Let's define a style sheet class for highlighted row.

<style type="text/css">

/*for gridview row hover, select etc*/










(The gridview markup shown above is only for example purpose. So you will not see any matches between the figure showing highlighted row and the example markup. Further you will also need to implement your own css styling, if you prefer any). Note the OnRowDataBound event handler in the gridview design markup. We will write some lines of code in this event handler to add the effect of highlighting gridview rows on mouse over. Here goes the code.

//row created event
protected void gridTest_RowCreated(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
e.Row.Attributes.Add("onmouseover", "this.className='highlightrow'");
e.Row.Attributes.Add("onmouseout", "this.className='normalrow'");

We have specified the css class to adapt by the gridview row on mouse over. At the same time, we need to assign another css class on mouse out so that the gridview will be highlighted only on mouseover and on mouse out the effect will be void. Happy programming!

kick it on pimp it Shout it

Tuesday, June 9, 2009

22 Visual Studio Short Keys and 6 Short-cut Ways to Custom Jobs: A List of Tips and Tricks

Efficient programmers use short keys in IDE like Visual Studio. This saves time and in many cases makes the work run faster also. I also love short keys. They are smart! And there also go some tricks that help make your visual studio days a party! I have listed here some short cuts and some tips with the hope that this will be helpful to you all.

Visual Studio Short-cuts

  1. Ctrl+F5 to run the website without debugging. F5 only will run the website in debugging mode.
  2. Stop Debugging: Shift+F5
  3. Restart Debugging: Ctrl+Shift+F5
  4. Break All: Ctrl+Alt+Break
  5. F11 to debug line by line downwards from the toggle point. This works with F10 also. In fact you can see F10 assigned for this task. See Debug menu in the visual studio.
  6. F9 to toggle a break point.
  7. To delete all the break points at once: Ctrl+Shift+F9. If you only wish to disable the break points you can go down the Debug menu.
  8. Ctrl+S to save the current document. Ctrl+Shift+S to save all the documents at once.
  9. Print a document directly from the visual studio? Press Ctrl+P. This will bring the print dialog.
  10. Ctrl+F to find a text. A find dialog will be displayed. Then you are left with a number of options.
  11. Ctrl+H or Ctrl+Shift+H for find and replace.
  12. Ctrl+G to go to the specific line number in the current document.
  13. Open the web browser right from within the visual studio? Press Ctrl+Alt+R.
  14. Irritated switching back and forth the design view and code behind page of a file? Use F7 to navigate back and forth the files of a page.
  15. Press F4 to view the properties window for a control from the design page.
  16. To view the server explorer: Ctrl+Alt+S
  17. To view the solution explorer: Ctrl+Alt+L
  18. To view the output window: Ctrl+Alt+O
  19. To view the toolbox: Ctrl+Alt+X
  20. Press Shift+Alt+Enter to view/undo full screen.
  21. Press Ctrl+O to open a document from the project folder.
  22. Ctrl+F11 to view disassembly: the machine level code!

Visual Studio Tips

  1. To view the start page, navigate View->Other Windows->Start Page
  2. To initiate the start page to display feed from a website, Tools->Options->Startup. Choose show start page at start from the combo fox. Input the start page news channel rss feed. Click Ok.
  3. To display line numbers in the documents, Tools->Options->Text Editor. Now click the editor you need to display number in. Check Line Numbers at the right side of the window.
  4. Initiate the home page for the web browser [opened by pressing Ctrl+Alt+R]? Follow Tools->Options->Environment->Web Brower. Set the home page and optionally the search page from the right side of the window.
  5. Know the class name or method name but confused the right namespace? Right click the class name or method name and click Resolve; you will see the reference you need to add. Click the reference. It will be added for the page.
  6. Using find window and clicking Find button each time to go to next match? Leave the trend. Just press F3 to go to next match!!

Shortcuts are the small but useful ladders of programming. You can use them to go up and down, left and right or south and north. I would like to heartily welcome to share your tips and tricks that you have learned from your dedicated play around with the visual studio. All the tips and shortcuts I have listed above are tested and learned from visual studio 2005. They may or may not work in visual studio 2008 and later versions. You can specify the compatibility of your trick that you are posting as comment in this article. Thank you very much. Happy Programming!

kick it on Shout it pimp it

Monday, June 8, 2009

How to read email address, host, port number from smtp settings section of web.config file in

How can I read the email address, smtp host, port number from my mail settings section of the web.config file in an web application? Yeah, we can specify an email address in the mail settings section of web.config file and read it from web page in the time of sending an email. We can also read the smtp host and port number which is necessary while sending email from an web page. I have already discussed: How to send email from web page. So here I would just put the coding to read email address, host, port number from mail settings section of web.config file in web application.

Let's look into the mail setting portion of a web.config file.




<network host="mymailhostaddress" port="25"/>




While sending an email, we need from, to email addresses and an smtp client also. So the code snippet below puts them together.

using System.Net.Mail;
using System.Drawing;
using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration;

//the method to send email
public void SendMail()
Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("") as MailSettingsSectionGroup;
SmtpSection smtpSection = mailSettings.Smtp;
//read the from email of the web.config file
string fromEmail = smtpSection.From;
int port = mailSettings.Smtp.Network.Port;
string host = mailSettings.Smtp.Network.Host;

//..other code follows from here
//that sends the email

//create new mailmessage object
MailMessage message = new MailMessage(new MailAddress(fromEmail), new MailAddress(""));
message.Body = "Hi. This is test message.";
message.Subject = "Test Message!";
message.IsBodyHtml = false;

//create smtp client and send mail
SmtpClient client = new SmtpClient(host, port);
lblError.Text = "Email sent successfully!";
lblError.ForeColor = Color.Green;
catch (Exception ex)
lblError.Text = "Email could not be sent. " + ex.Message;
lblError.ForeColor = Color.Red;

Using the code above, we easily accessed the important information from mail settings section of the web.config file. Please note again that I have just put the coding of reading information form web.config file. You can learn from here to Send Email in web page so that you can combine what this article provides with sending email in web application. Happy Programming!

kick it on Shout it pimp it

Tuesday, June 2, 2009

How to extract data out of your datacontrol ( formview, detailsview or gridview) using FindControl or ExtractValuesFromCell method?

Most of the times programmers need to extract data out of the datacontrols like formview, detailsview or gridview. Mostly we use FindControl method of the data control for this purpose. And another method ExtractValuesFromCell is also entertained to achieve the goal. It would be very interesting to throw a little light upon both of them.

Naturally I am familiar with the FindControl method of the datacontrols. For example, to find a dropdownlist in the formview or detailsview control, I would call:

DropDownList ddlTest=FormView1.FindControl("DropDownList1") as DropDownList;

Similarly, we could search for an control in a particular row of a gridview control. For example:

GridViewRow row=GridView1.Rows[5]; // here we are dealing with the fifth row
TextBox textName=row.Cells[2].FindControl("textboxName") as TextBox; //here, there is a textbox with id textboxName in the second cell of the row
if(textName!=null) //check if such textbox was found in the specified cell or the specified row
string name=textName.Text;

Practically we need to get a control from the data control in special events of the control like inserting, inserted, updating, updated, deleting, deleted, selectedindexchanging, selectedindexchanged etc. Combining the FindControl method with such event handlers help customize data during data operations (add,edit,delete) and provides flexibility to display data from database or other data sources (xml, csv, programmatically created datatables etc).

Before discussing ExtractValuesFromCell, I would like to drop one note. Please note that some standard controls in some data controls may be available for extracting only in the particular mode of the data controls. Confusing? Don't worry. This simple example will clarify it. Say, we do have a textbox in the edititemtemplate of a detailsview. To reference this textbox and extract value from it, we can use the findcontrol method only if we are in edit mode. In other modes we will get null reference (and possibly null reference exception may be thrown when we try to extract text or other properties). That is why I have checked for the null in the code above before reading text value from the textbox.

Now let's focus on ExtractValuesFromCell. There goes a popular article on Extracting data out of your datacontrol which discusses ExtractValuesFromCell method to get data from the controls in datacontrols like gridview, formview or detailsview. (The title of this article is inspired from it! And I have tried to make it as useful as I can). Please refer to the heavily discussed article to understand what the author davidfoul has discovered and what are the benefits of using ExtractValuesFromCell method to extract data out of a datacontrol.

After you have been through the article, you sure would like to ask which method to use- FindControl or this ExtractValuesFromCell? This is what I commented to the author:

Hi dear author,

I came here following the discussion on the forum:

I have always been using FindControl() method: much easier and handy. You need not to write (and call everytime) the functions to extract values (or cells) using ExtractValuesFromCell.

This ExtractValuesFromCell way of extracting values from cell is just another way around it. So what's wrong to go with FindControl. Please give your opinion (perhaps you could update the post to add a sections: Why to not use FindControl(); I am requesting this because the argument among developers would go longer!).

Hey, this could be the advantage: People sometimes ask how to get all the values from my gridview since I have been editing and updating it, so changing the original value from the datasource. In such case this trick could help a lot.


And our generous author davidfoul has replied his kind views:

@sangam100 I had this same question about FindControl on the forum. Here is what I said:

It's not the use of FindControl that makes my spine tingle its the MISuse and ABuse of it that does. FindControl is a good method and very useful, but look at the name of method, FindControl. Everything has a purpose right? If I'm trying to find a control then i'll call find control. If I'm trying to get data out of a control I might call find control or some other API that is better at getting data, i.e ExtractRowValues. I think that there is alot of knowledge out there, good and bad, about using these data controls and I just want to try to set some things straight by shedding some more light on how stuff works (I love that website).

Before I go lemme show you what I mean by picking the right API.  Lets make a new control IntControl. IntControl has a method int GetValue(). Now OO principals tell us to not break the abstraction by letting consumers grab at the internals but IntControl derives from control, and by default, there is alot of other things exposed to the consumer that shouldn't be. Now we know that IntControl uses a textbox internally so I could never call GetValue and instead write:

int value;

Int32.TryParse(((TextBox)IntControl.Controls[0]).Text, out value);

Everything will work fine until the author of IntControl decides to use a div instead of a textbox.

The REAL lesson to take away from the blog post is to try your best to follow the contract provided by a class or an interface (in this case the DataControl).

You can read comments, views, suggestions of so many enthusiastic web developers both in the original site by the author and a post in the Please comment in the respective sites to put your opinions to the articles. However you can comment as always on this article regarding my perspectives. Thank you. Happy Programming!

kick it on Shout it pimp it

Monday, June 1, 2009

How to send email from Basic C# code to send simple email

Sending email in is very useful and customizable too. The powerful classes help you compose and send email in minute! The glamour has always fascinated me, but more important is the frequent questions that are asked in related forums on sending email in using C# or We can send email using some smtp server. And if this is not viable (sometimes we don't have smtp accounts!) we can use our own gmail account to send email (Thank you gmail!)

Take one example- Here goes the question that was asked in forum-

"can someone give me code how to send an e-mail from c# code
I am working with a company using Microsoft outlook for my mails.
I want to send mail only to 1 person, also please help me in identifying "smtp hostname"

Here goes the simple and helpful answer.

Visiting all above listed links you must have realized that sending email in is quite fun and useful too. In fact, a lot of customizations exist depending on your requirement. My suggestion is to do the basic email sending first. After that you can play with the classes and objects to perform more actions. Let me show you the basic email sending using c#.

//sending basic mail in 
public void SendBasicMail()
//create new mailmessage object
MailMessage message = new MailMessage(new MailAddress(""), new MailAddress(""));
message.Body = "Hi. This is test message.";
message.Subject = "Test Message!";
message.IsBodyHtml = false;

//create smtp client and send mail
SmtpClient client = new SmtpClient("", 25);
lblError.Text = "Email sent successfully!";
lblError.ForeColor = Color.Green;
catch (Exception ex)
lblError.Text = "Email could not be sent. " + ex.Message;
lblError.ForeColor = Color.Red;

This simple example will help you understand the basics of sending email in web application.

Now interested in sending email using our own gmail account? Here goes the coding by getchinna_sv (Thank you getchinna_sv! Yours sangam100).

 protected void sendMail()
string from = ""; //Replace this with your own correct Gmail Address
string to = ""; //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.From = new MailAddress(from, "One Ghost", 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;

SmtpClient client = new SmtpClient();
//Add the Creddentials- use your own email id and password
client.Credentials = new System.Net.NetworkCredential(from, "Password");
client.Port = 587; // Gmail works on this port
client.Host = "";
client.EnableSsl = true; //Gmail works on Server Secured Layer
catch (Exception ex)
Exception ex2 = ex;
string errorMessage = string.Empty;
while (ex2 != null)
errorMessage += ex2.ToString();
ex2 = ex2.InnerException;
} // end try

client.Credentials = new System.Net.NetworkCredential(from, "Password"); in this statement... write your gmail password.... from address should be a gmail address....

Hope this post will help. Thank you. Happy Programming!

kick it on Shout it pimp it

Dropdownlist selected item validation fails: the suggestion

Today I got across a question in the forum which seems simple but is still confusing for many beginners. So I am giving a place for it here:


Hi Everyone,

I'm trying to set some error handling by returning a message when a button is clicked and the user has not selected an item from the dropdown menu. I'm using this but for some reason it is being ignored?

protected void validatebtn_Click(object sender, ImageClickEventArgs e)
if (!(DropDownList1.SelectedValue == "Select Item"))
lblerrors.Text = "
You have not selected an item from the drop down list.";
//...continue with the code.

When I debug the code, it reads the first line:

if (!(DropDownList1.SelectedValue == "Select Item"))
and then skips to the else statement and misses my message?

Can anyone advise why this is happening?

Chloe ~X~

Among other suggestions, here is what I have suggested:


Looking into your explanation and reading all the answers given by members, some questions came in my mind.

1. Did you check what value is exactly selected from the dropdownlist? I mean DropDownList1.SelectedValue should be "Select Item" only then your comparision will be true.
2. Are you adding this "Select Item" from design view or is it added programmatically from code behind? Did you only specify "text" or both text and value? See the markup below:

<asp:DropDownList ID="ddlTest" runat="server">
<asp:ListItem Text="Select Item" Value="Select Item" Selected="True"></asp:ListItem>

If you don't put Selected="true", this item may display at the first position, but is not selected yet. So don't forget to set this. Another thing to notice is you should have set both Text and Value. The "SelectedValue" corresponds to the "Value" in the markup. Only then your code will work. Don't forget to have both text and value if you add listitem to the dropdownlist from codebehind, like this one:

ListItem item = new ListItem("Select Item", "Select Item");

Hope this helps. Please feel free to ask if the problem persists or if further help is required. Thanks.

kick it on Shout it pimp it

Friday, May 29, 2009

Check uncheck all rows of gridview (select or deselect all rows at once)

The gridview data control offers lots of features, that we all know. Adding some cool effects may make this control more usable. For instance, we could check or uncheck all the checkboxes in a column of the gridview control. A column [leftmost column usually] consisting of checkbox control is generally used to select a row. Sometimes we may need to check (and uncheck) all the rows of the gridview. Purpose of doing so may be different depending upon the business requirement. And if we need to do so, we can!

Fig. Check Uncheck all rows in a gridview

Let's be quick to implement check/uncheck all the rows of gridview at once in gridview. Let's have the markup for the gridview first.

<asp:GridView ID="gvTest" Width="100%" runat="server" AutoGenerateColumns="false">


<asp:TemplateField HeaderText="Select" HeaderStyle-HorizontalAlign="center" ItemStyle-HorizontalAlign="center">

<HeaderTemplate >

<input id="chkAll" onclick="javascript:SelectDeselectAllCheckboxes(this);"

runat="server" type="checkbox" />



<asp:CheckBox ID="chkSelect" runat="server" />



<asp:BoundField HeaderText="Name" DataField="Name" ItemStyle-Width="100" />

<asp:BoundField HeaderText="Address" DataField="Address" />



Watched the checkbox control in the header template of the first column? We will use this checkbox to select or deselect all the rows in the gridview. Also mark that clicking this checkbox will call the javascript function SelectDeselectAllCheckboxes. Now is the time to define some javascript snippets to get help from.

<script type="text/javascript">  

function SelectDeselectAllCheckboxes(spanChk){

// Added as ASPX uses SPAN for checkbox

var oItem = spanChk.children;

var theBox= (spanChk.type=="checkbox") ? spanChk : spanChk.children.item[0];




if(elm[i].type=="checkbox" && elm[i].id!









The task done by the javascript function is simple. It takes the checkbox itself as the input. If it is checked, it searches for all the checkboxes in the gridview and checks them. And reversely, if it is unchecked, all those checkboxes will be consequently unchecked.

There is no need of any codebehind just for this functionality. So I am leaving other parts including databinding code. In fact, for most of the test purposes I do Create DataTable Programmatically and bind the gridview, formview or detailsview to that DataTable.

The only drawback with this technique is that it treats all the checkboxes in or outside the gridview control equal.

You can post your comment, rate this post or add this post to your favourites or share it. Happy Programming!

kick it on Shout it pimp it

Wednesday, May 27, 2009

Fill formview textbox to initial value in insert mode

In most scenarios, the data controls like detailsview and formview have empty controls in insert mode. This means any field that requires [or at least expects] user input will not contain any data. But this default configuration sometimes needs to be modified. Say, we would like to fill the date field in a textbox to current date, so that it will be easier for user. This is just an example. This can be the dropdownlist from where we would like to select one value initially, or it may be other user input control like checkbox or radiobutton. In such scenario, we can set the control value to some default initial value. With datacontrols like formview and detailsview, it takes a little effort [simple and tricky!]. In this short post [In fact I am expecting to keep this post as such as possible since there is no need of much explanation: concept is crystal clear and implementation is also easy!] I am going to show the simple coding practice to initiate the formview or detailsview control to some value. I will be choosing formview to show the example.

Fig: Setting a textbox to an initial value in insert mode of an formview control

The formview can have one of three modes at one instance of time. They are Insert, Edit and ReadOnly modes. We should be careful about the current mode of the formview before we do reference any control. This is because a textbox in edit template may not be available in the read only mode, for instance. So we will check the current mode of the formview and search for the textbox with its ID. Then we can easily set the value of the control. Let's have a formview first.

FormsView Design Markup

<asp:FormView ID="FormView1" runat="server" HeaderText="Fill the Credentials below." DefaultMode="Insert">





Name: <asp:Label ID="lblName" runat="server"></asp:Label>





Date of Test: <asp:Label ID="lblTestDate" runat="server"></asp:Label>









Name: <asp:TextBox ID="txtName" runat="server"></asp:TextBox>





Date of Test: <asp:TextBox ID="txtTestDate" runat="server"></asp:TextBox>






We simply have two fields in the formview: name and date of test. Our intension will be to initiate the value of the date of test field to current date.

CodeBehind for the example

protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
//Call to filling textbox in the insert mode;
//I assume here that initially the formview
//is in insert mode

public void FillDefaultVaueInFormView()
//if the formview is in insert mode
if (FormView1.CurrentMode == FormViewMode.Insert)
//txtTestDate is the id of the 'date of text' textbox in formview
TextBox txtTest = FormView1.FindControl("txtTestDate") as TextBox;
if (txtTest != null)
txtTest.Text = DateTime.Now.ToShortDateString();

Now the formview will have the date of test field initiated to the current date. Let me repeat- Simple and Tricky! You can post your comments and suggestions from the form below. You can rate this post as well. You can even share this post. Just add this post to the social sites! Happy Programming!

kick it on Shout it pimp it

Friday, May 22, 2009

Click the button on keypress in TextBox

In this post, I am explaining the button click functionality on key press in a textbox. I am using javascript to link the input textbox and the associated button that has to be clicked when the enter key is pressed in the textbox. One can preview it by taking the example of search textbox and GO button!

Fig. Clicking button on enter key press in textbox

We have seen search textboxes in almost all of the websites which imply 'Go' or 'Search' button click when Return key (Enter key) is pressed. Naturally, users love to press enter key instead of clicking search button next to the input textbox. Wouldn't it be nice if we could do the same for our web pages also? Yeah, I have implemented the button click feature on keypress in textbox control many times. But the last time practice on a web application that added both the textbox and the search button dynamically via javascript was really interesting story that inspired me to re-share the code [since I also learnt it on Internet].

Design Page Markup (SearchPage.aspx)
We do have one textbox and one button in the search page.


Search Text: <asp:TextBox ID="txtSearchBox" runat="server"></asp:TextBox>

<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />


JavaScript Code    
This javascript code will be invoked when enter key is pressed in the textbox.


function clickButton(e, buttonid){

var evt = e ? e : window.event;

var bt = document.getElementById(buttonid);

if (bt){

if (evt.keyCode == 13){;

return false;





We put this javascript code snippet within the head section of the design page.

Code Behind (SearchPage.aspx.cs)

//page load event handler
protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
//add attribute on the search textbox
//so that when enter key is pressed in the textbox,
//the search button will be fired
txtSearchBox.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearch.ClientID + "')");

//when search button is clicked
protected void btnSearch_Click(object sender, EventArgs e)
//my function to perform search

Here we add the onkeypress attribute to the textbox. When a key is pressed, the keycode will be passed to the javascript function. The javascript function checks if this is the enter key, and it is enter key then the button click is invoked by the javascript code.

So far we implemented button click on enter key press from an web control. To add a little user interactivity in the search textbox, you can implement google search like watermark effect in the search textbox. If you further want to prevent multiple postback, you can just disable button after first click and enable after postback completes.

Don't forget to expose your views via comment box beneath this post. You can freely share this post! Happy Programming!

Shout it kick it on 

Monday, May 18, 2009

Contact Me

Thank you!

Dear reader,

Thank you for taking time to drop your feedback/suggestion/query. An email has been sent to you to confirm your action. I will be listening you very soon!

You can now go to dotNETspidor home page and enjoy your day!

Thank you very much. Have nice dotNETspidor surfing!

About Me

My name is Sangam Uprety, a computer engineer from Nepal. For 2 years I have been programming web applications. I do love playing with javascript and ajax for client side programming. I do program SQL Server and Oracle databases. I also code DotNetNuke (DNN) modules for portal development. In fact developing multi-featured portals is my passion!

Besides programming, I love reading books. Songs? Obviously, all kinds! I don't find myself anywhere if there are no social activities in my life. I believe social works have always saved nations.

I love watching football games. Ok..ok..did I mention I do write also? If I didn't, no problem. I love writing. Thanks goes to Karl Marx who said that people who write diaries never fail! And I do run a blog. Yeah, dotNETspidor: A dot net programming blog !

Would like to contact me or just drop me some words? Ok, you are heartily welcome to Leave Your Valuable Message/Feedback/Suggestions right from this blog!

Thank you for being interested about me!

List all files in a folder in an gridview

We do have a folder (and a number of sub folders) with a number of various files in those folders (and sub folders). Now we do need to list all those files in an gridview control [for the purpose of organizing those files, or for the preview of files uploaded till now, say]. We can do it in using the System.IO namespace. In this article, I am going to show the coding for displaying all files in a folder in an gridview. In fact, as a bonus, we will do the listing of all files in a root folder and all its subfolders also.

Fig: Snapshot of displaying all files in a folder and its subfolders in an gridview control

Design Page Markup (ListFiles.aspx)
We first need to have a web page with the gridview control in it.

<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">

Remember, we have set the AutoGenerateColumns field to true. So all the fields that is present in our source will be displayed by the gridview, each as a separate column. (I have removed the formatting of the gridview markup to make the code clear. Please your own formatting for the gridview.)

Code behind page (ListFiles.aspx.cs)
Now here goes the actual code to bind all the files in the folder "Resources", that resides at the root of the web site, and all its subfolders.

protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)

public void GetFilesAndFolders()
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("~/Resources"));
FileInfo[] fileInfo = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);
GridView1.DataSource = fileInfo;

We have used the DirectoryInfo and FileInfo classes of the System.IO namespaces. The DirectoryInfo class will get the root directory of the provided folder name. And we have used the DirectoryInfo class's GetFiles method. This method has two overloads. We can specify the file patterns (e.g. "*.txt" for text files only, or "*.*" for all types of files etc) and the search option- if to list all the files in all the subdirectories of the root directory (in our case, "Resources" folder) provided as the input, or just to list the files in the root directory.

When we browse the page, we see the gridview populated with 13 fields, which I hope need no explanation. However for your reference I have listed the fields here: LastAccessTimeUtc, Length, LastWriteTime, LastWriteTimeUtc, FullName, IsReadOnly, CreationTimeUtc, LastAccessTime, CreationTime, Name, Exists, Extention, and DirectoryName. For the description of each field, please visit FileInfo class Properties, msdn document.

Now from those thirteen fields, we can choose and display the required ones. Please don't forget to share your views, suggestions or comments as always. Thank you. Happy programming!

kick it on pimp it Shout it

Popular Posts

Recent Articles