google

Newest Post

Top HR Interview Question - Tell Me About Yourself??

| Thursday, February 28, 2013
Read more »
Do you know why this question is asked so often in most job interviews? This question is actually an ice-breaker. Asking this question starts the conversion. So you should better be ready with an answer. This question gives the interviewer a chance to know about the interviewee. Once you start talking about yourself, interviewer starts preparing his/her next question. So there are high chances that the next question that would be fired on you will be based on the answer of this question. As the answer for this will be based on you, you think and prepare it before the interview.

While preparing for the answer consider including following points.
1. You:
Tell them your name and which place you are from. Suppose you are “Mike Creamer”, then do not start with “Myself Mike Creamer”; start with “I am Mike Creamer”. This is a very common mistake. Not acceptable in interviews especially in call center jobs.
You may talk about your family (cover up in short); you may talk about your how you came to the city, etc.

2. Your education:
Tell them about your education i.e. graduation/post-graduation. If you are a fresher then tell them the grades you got. If you have done something different than others then tell them. It surely adds a value!

3. Your experience:
Talk about your whole experience. Start from early years and gradually come to recent years. If you have a long experience then you must not be doing same thing all years. Then exactly what you were doing? This is what your interviewer wants to listen. If you are a fresher then talk about your projects.

4. Your experience regarding to the post you has applied for:
This is of most interest to your interviewer. You may be having lot of experience but how much experience you have regarding current job post is very important. If you do not have it then you can talk about some related experience. Or if you do not have related experience too then say it clearly. Buy along with it give them confidence that you can do it and you have genuine interest to do it.

Fresh candidates who do not have any kind of experience, you should show some positive attitude and exhibit willingness to learn and do new things. Be ready to do new things. Don’t worry that you will make mistakes. Fresher candidates are expected to do mistakes and your employers are well aware of it so you don’t have any reason to be afraid. Believe me no one will give you more work than you can handle.



5. Do not describe your salary or pay scale at this point of time (unless explicitly asked).

6. Avoid giving unnecessary details. Value your interviewer’s time.

7. The idle answer should not last more than 1 minute.

Good luck.

Article from - http://careercounselings.net/top-hr-interview-question-tell-me-about-yourself/

Top HR Interview Question - Tell Me About Yourself??

Posted by : Stranger
Date :Thursday, February 28, 2013
With 0comments

Extending the Named and Optional Parameters

| Tuesday, February 26, 2013
Read more »
In Named and Optional Parameters, article illustrates about the named and optional parameters. In this article I am extending this article to differentiate between parameters ,arguments and more about optional parameters.

The parameter is a variable which is the part of the method, however argument is the variable which invoke in the place of parameter.

Arguments initialize parameters.


 public void Method(string parameter)  
 {   
   txtString.Text = parameter;  
 }  

When this method is called then argument is passed.

 Method(argument);  

Little bit more about the Optional Parameters

Optional parameters restrictions

  1. Ref or out modifiers not allowed.
  2. Paramsarray is not allowed as optional, and must be the last parameter.
  3. Optional parameters must be written after required parameters.
  4. Default value of optional parameter must be a Compile-time constant.

Extending the Named and Optional Parameters

Posted by : Stranger
Date :Tuesday, February 26, 2013
With 0comments
Tag :

Apple iOS development extended to Visual Studio

| Friday, February 22, 2013
Read more »

Apple iOS development extended to Visual Studio

Posted by : Stranger
Date :Friday, February 22, 2013
With 0comments
Tag :

what is cloud computing for beginners | Developers Code

| Wednesday, February 20, 2013
Read more »

what is cloud computing for beginners | Developers Code

Posted by : Stranger
Date :Wednesday, February 20, 2013
With 1 comments:

Why good employees leave???

|
Read more »

Why good employees leave???

Posted by : Stranger
Date :
With 5comments

Custom UIPickerView with multiple Columns

| Tuesday, February 19, 2013
Read more »
Display multiple columns in UIPickerView.

Custom UIPickerView with multiple Columns

Custom UIPickerView with multiple Columns

Posted by : Stranger
Date :Tuesday, February 19, 2013
With 1 comments:
Tag :

Adding Custom Code Snippet in XCode

|
Read more »
Following article demonstrates the steps of adding custom code snippets in Xcode
 
Adding Custom Code Snippet in XCode

Adding Custom Code Snippet in XCode

Posted by : Stranger
Date :
With 0comments
Tag :

Google Maps in asp.net website with dynamic addresses from database.

| Monday, February 18, 2013
Read more »
Add following javascript in the head section of the page to access the google maps API.
 <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false"></script>  

Add following javascript code in the head section of the page to access the google api functions to display the map on the page.

 <script>  
     var geocoder;  
     var map;  
     function initialize() {  
       geocoder = new google.maps.Geocoder();  
       var latlng = new google.maps.LatLng(-34.397, 150.644);  
       var mapOptions = {  
         zoom: 8,  
         center: latlng,  
         mapTypeId: google.maps.MapTypeId.ROADMAP  
       }  
       map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);  
     }  
     function codeAddress() {  
       var address = document.getElementById('<%= hdnAddress.ClientID %>').value;  
       //alert(address);  
       geocoder.geocode({ 'address': address }, function (results, status) {  
         if (status == google.maps.GeocoderStatus.OK) {  
           map.setCenter(results[0].geometry.location);  
           var marker = new google.maps.Marker({  
             map: map,  
             position: results[0].geometry.location  
           });  
         } else {  
           alert("Geocode was not successful for the following reason: " + status);  
         }  
       });  
     }  
   </script>  

Above functions can be called "onload" by adding the "onload" attribute to the body tag as follows

 <body onload='initialize();'>  

Also this javascript can be called from the server side by registering the script in "Page_Load" event of the class.

 ClientScript.RegisterStartupScript(GetType(), "show", "initialize();", true);  
 ClientScript.RegisterStartupScript(GetType(), "show1", "codeAddress();", true);  

An ASP.NET hidden control is used to store the address of the location obtained from the database. Value to "hdnAddress" can be assigned from server side or client side as per the functionality of the page.

Following "div" element is added on the page to display the map on the webpage.

 <div id="map_canvas" style="width: 285px; height: 275px;"></div>  
  </div>  

The output on the browser will be
Size of the div with id "map_canvas" can be altered by changing the "height" and "width" attributes of the div element.

Try and Enjoy Coding!

Note - Please provide your feedback and let me know if there is any problem with above code.

Google Maps in asp.net website with dynamic addresses from database.

Posted by : Stranger
Date :Monday, February 18, 2013
With 3comments

Simple jQuery Image Slideshow Example with Text Overlay in Asp.net

|
Read more »
Simple jQuery image slideshow example with text overlay or Simple jQuery image slideshow with caption or jQuery image slideshow with content or jQuery image slideshow with links in asp.net.

 
Simple jQuery Image Slideshow Example with Text Overlay in Asp.net

Named and Optional Parameters

| Saturday, February 16, 2013
Read more »
With the introduction of C# 4.0, named and optional parameters have been included in the language. They can be used to enhance the readability of source code and simplify some calls by specifying which parameters the argument values refer to.

Named parameters enable us to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list.

Optional parameters enable us to omit arguments for some parameters. 

Both techniques can be used with methods, indexers, constructors, and delegates.With named and optional parameters, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.

Named and optional parameters, when used together, enable us to supply arguments for only a few parameters from a list of optional parameters. This capability greatly facilitates calls to COM interfaces such as the Microsoft Office Automation APIs.

Named Parameters
When a method is called with named arguments/parameters, they free us from the constrain of remembering the order of parameters to be passed to the method. Parameters can be passed in any order and compiler allocates temporary local memory for those named parameter variables

e.g

 public int Volume(int height, int length, int breadth)  
     {  
       return height * length * breadth;  
     }  

The above method can be called like this:


 protected void Page_Load(object sender, EventArgs e)  
     {  
       int result = Volume(10, 10, 10);  
       int result2 = Volume(length:10,height:10,breadth:10);  
     }  

int result = Volume(10, 10, 10);
It calls the Volume method by sending arguments in order of position of arguments.

int result2 = Volume(length:10,height:10,breadth:10);
It calls the Volume method by sending arguments with named parameters.

We can mix named and unnamed arguments in a call as long as all of the unnamed arguments appear before any named ones. The unnamed arguments will be applied in the order that they appear in the method’s signature.

 Optional Parameters 
The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters.
Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used.

e.g

 public void ExampleOptional(int required, string optionalstring = "hello", int optionalint = 10)  
     {  
     }  

Above method can be called like this:

  protected void Page_Load(object sender, EventArgs e)  
     {  
       ExampleOptional(3, ,4); //This line will cause compiler error,because an argument is provided for the third parameter but not for the second  
       ExampleOptional(3, optionalint: 4);  
     }  

IntelliSense uses brackets to indicate optional parameters.

Named and Optional Parameters

Posted by : Stranger
Date :Saturday, February 16, 2013
With 0comments
Tag :

Google Checkout implementation on ASP.NET

| Friday, February 15, 2013
Read more »
To integrate Google Checkout on ASP.NET.

Google Checkout implementation on ASP.NET

For Visual studio 2010/2012, Nuget package for Google Checkout is also available. Download the Google Checkout Nuget from following link:

Nuget.Google.Checkout

Google Checkout implementation on ASP.NET

Posted by : Stranger
Date :Friday, February 15, 2013
With 0comments

Show Message Bar at the top of the page using HTML and jQuery

| Wednesday, February 13, 2013
Read more »
Download Code

This article will focus on displaying notifications or messages at the top of the website page using HTML and jQuery.

Links to required jQuery files will be added in the head section of the page.

  <script src="jquery.js" type="text/javascript"></script> 
 <script src="juery.topbar.js" type="text/javascript"></script>  


The source code includes 4 types of demonstrations of the top message bar.Following script will be included in the head section of the page


  <script type="text/javascript" language="javascript"> 
$(function () { 
$("#ex01").click(function () { 
$('#ex01-body').showTopbarMessage(); 
}); 
$("#ex02").click(function () { 
 $('#ex02-body').showTopbarMessage({ close: 2000 }); 
 }); 
$("#ex03").click(function () { 
 $('#ex03-body').showTopbarMessage({ background: "#043", close: 2000 }); 
 }); 
$("#ex04").click(function () { 
 $('#ex04-body').showTopbarMessage({ height: "180px", close: 2000 }); 
 }); 
 }); 
</script>  


Following types of demonstrations are there:

1. Simple

  <p> 
<a href="javascript:void(0)" id="ex01">Simple</a>     </p> 
<pre>$("#ex01").click(function () { 
 $('#ex01-body').showTopbarMessage();   });</pre> 
 <div id="ex01-body" style="display: none;"> 
 This is a simple demo 
 <span style="font-size: small; cursor: pointer">(click to close)</span> 
 </div>  

2. Automatic close after some time.

  <p> 
 <a href="javascript:void(0)" id="ex02">Automatic close after some time</a> 
 </p>     <pre>$("#ex02").click(function () { 
 $('#ex02-body').showTopbarMessage({ close: 2000 });   });</pre> 
 <div id="ex02-body" style="display: none;"> 
 Automatic close after some time     </div>  

3. With custom background

  <p> 
 <a href="javascript:void(0)" id="ex03">With Custom background</a> 
 </p>     <pre>$("#ex03").click(function () { 
 $('#ex03-body').showTopbarMessage({ background: "#043", close: 2000 }); 
 });</pre>     <div id="ex03-body" style="display: none;"> 
 With Custom background     </div>  

4. Custom height with long text

 <p> 
 <a href="javascript:void(0)" id="ex04">Custom height with long text</a> 
 </p>     <pre>$("#ex04").click(function () { 
 $('#ex04-body').showTopbarMessage({ height: "180px", close: 2000 });   });</pre> 
 <div id="ex04-body" style="display: none;"> 
 Custom height with long text.<br /> 
 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum 
 </div>  


Show Message Bar at the top of the page using HTML and jQuery

Posted by : Stranger
Date :Wednesday, February 13, 2013
With 0comments

ImageLens – A jQuery plug-in for Lens Effect Image Zooming

|
Read more »

ImageLens – A jQuery plug-in for Lens Effect Image Zooming

Posted by : Stranger
Date :
With 0comments
Tag : , ,

Create Tooltips, Modal Windows, Notice Messages using MooTools mBox library

| Tuesday, February 12, 2013
Read more »

mBox 0.2

mBox is a powerful library, helping you to easily create tooltips, modal windows, notice messages and more.
Styling is stress free with css and there are many options to customize position, appearance, events etc.

Check this out - mBox



Create Tooltips, Modal Windows, Notice Messages using MooTools mBox library

Posted by : Stranger
Date :Tuesday, February 12, 2013
With 0comments

Random number generator function in C#

|
Read more »

Random number generator function in C#

Posted by : Stranger
Date :
With 0comments
Tag :

For a sneak peek into RESTful services API - What is REST?

| Monday, February 11, 2013
Read more »
For a sneak peek into RESTful services API.

For a sneak peek into RESTful services API - What is REST?

For a sneak peek into RESTful services API - What is REST?

Posted by : Stranger
Date :Monday, February 11, 2013
With 0comments

Asp.Net Bind Populate DropDownList With JQuery And XML

| Saturday, February 9, 2013
Read more »
Check this out to bind the drop down with jquey n XML


Asp.Net Bind Populate DropDownList With JQuery And XML

Asp.Net Bind Populate DropDownList With JQuery And XML

Posted by : Stranger
Date :Saturday, February 9, 2013
With 0comments
Tag : , ,

jQuery Star Rating Plugin v3.14

|
Read more »

jQuery Star Rating Plugin v3.14

Posted by : Stranger
Date :
With 0comments

LPU received the Shiksha Ratan award for "UMS"

|
Read more »
Lovely Professional University received the Shiksha Ratan award for best IT initiative in Higher Education through its unique product named "University Management System".

Mr. Rohit Dhand, Additional Dean - Infotech Division receiving the prestigious Shiksha Ratan Award.




Team Infotech


LPU received the Shiksha Ratan award for "UMS"

Posted by : Stranger
Date :
With 0comments

Embedding Google Map in website with dynamic address from database.

| Friday, February 8, 2013
Read more »
Add following javascript in the head section of the page to access the google maps API.
 <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false"></script>  

Add following javascript code in the head section of the page to access the google api functions to display the map on the page.

 <script>  
     var geocoder;  
     var map;  
     function initialize() {  
       geocoder = new google.maps.Geocoder();  
       var latlng = new google.maps.LatLng(-34.397, 150.644);  
       var mapOptions = {  
         zoom: 8,  
         center: latlng,  
         mapTypeId: google.maps.MapTypeId.ROADMAP  
       }  
       map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);  
     }  
     function codeAddress() {  
       var address = document.getElementById('<%= hdnAddress.ClientID %>').value;  
       //alert(address);  
       geocoder.geocode({ 'address': address }, function (results, status) {  
         if (status == google.maps.GeocoderStatus.OK) {  
           map.setCenter(results[0].geometry.location);  
           var marker = new google.maps.Marker({  
             map: map,  
             position: results[0].geometry.location  
           });  
         } else {  
           alert("Geocode was not successful for the following reason: " + status);  
         }  
       });  
     }  
   </script>  

Above functions can be called "onload" by adding the "onload" attribute to the body tag as follows

 <body onload='initialize();'>  

Also this javascript can be called from the server side by registering the script in "Page_Load" event of the class.

 ClientScript.RegisterStartupScript(GetType(), "show", "initialize();", true);  
 ClientScript.RegisterStartupScript(GetType(), "show1", "codeAddress();", true);  

An ASP.NET hidden control is used to store the address of the location obtained from the database. Value to "hdnAddress" can be assigned from server side or client side as per the functionality of the page.

Following "div" element is added on the page to display the map on the webpage.

 <div id="map_canvas" style="width: 285px; height: 275px;"></div>  
  </div>  

The output on the browser will be
Size of the div with id "map_canvas" can be altered by changing the "height" and "width" attributes of the div element.

Try and Enjoy Coding!

Note - Please provide your feedback and let me know if there is any problem with above code.

Embedding Google Map in website with dynamic address from database.

Posted by : Stranger
Date :Friday, February 8, 2013
With 0comments

World Cancer Day (4 February 2013)

| Monday, February 4, 2013
Read more »
World Cancer Day 2013 (4 February 2013) will focus on: Dispel damaging myths and misconceptions about cancer, under the tagline “Cancer - Did you know?”
World Cancer Day is a chance to raise our collective voices in the name of improving general knowledge around cancer and dismissing misconceptions about the disease. In addition to being in-line with our global advocacy goals, we believe these overarching myths leave a lot of flexibility for members, partners and supporters to adapt and expand on for their own needs.


From a global level, we will be focusing our messaging on four myths. Learn the truth and supporting evidence, by clicking on the myths below.
Myth 1: Cancer is just a health issue
Myth 2: Cancer is a disease of the wealthy, elderly and developed countries
Myth 3: Cancer is a death sentence
Myth 4: Cancer is my fate

Myth 1 - Cancer is just a health issue

Truth: Cancer is not just a health issue. It has wide-reaching social, economic, development, and human rights implications.

Myth 2 - Cancer is a disease of the wealthy, elderly and developed countries

CIAN Agency © François Struzik - simply human - Tdh-02
Truth: Cancer is a global epidemic. It affects all ages and socio-economic groups, with developing countries bearing a disproportionate burden.

 

CANCER AND DEVELOPMENT

Cancer constitutes a major challenge to development, undermining social and economic advances throughout the world.

Myth 3 - Cancer is a death sentence

Truth: Many cancers that were once considered a death sentence can now be cured and for many more people, their cancer can be treated effectively.

ADVANCES IN CANCER PREVENTION AND TREATMENT

Advances in understanding risk and prevention, early detection and treatment have revolutionised the management of cancer leading to improved outcomes for patients.


Myth 4 - Cancer is my fate

CIAN Agency © François Struzik - simply human
Truth: With the right strategies, a third of the most common cancers can be prevented.

CANCER PREVENTION

Prevention is the most cost-effective and sustainable way of reducing the global cancer burden in the long-term.


Also with an ever-growing list of alarmist headlines, we asked some of the world’s leading cancer experts to separate the real dangers from the scare stories.(www.msn.com)
  1. According to the American Cancer Society, tobacco use accounts for at least 30% of all cancer deaths and 87% of lung cancer deaths. “The evidence is rock solid. It’s in a category of its own,” says Sara Hiom, director at Cancer Research UK. So if you want to reduce your cancer risk – stub out that cigarette today.

  2. A large European study, carried out by researchers from the German Institute of Human Nutrition in Potsdam-Rehbruecke looked at how current and former alcohol consumption related to the development of cancer in more than 350,000 people from eight countries. The researchers extrapolated the results to the general population and estimated that, across Europe, 10% of all cancers in men and 3% of all cancers in women could be attributed to alcohol consumption. “There is very strong evidence that all types of alcoholic drinks increase the risk of a number of cancers,” says Kate Mendoza from World Cancer Research Fund but there is no need to abstain completely – just cut down if you are drinking a lot. “We recommend limiting intake to two units a day,” says Mendoza.
  3. Red meat could be a contributor to cancer – especially bowel cancer. “There is evidence to suggest a link,” Hiom says. One possible reason for this is that the compound that gives red meat its colour, haem, may damage the lining of the bowel. People eating 160g a day increase their bowel cancer risk by a third, compared to those who eat 20g a day – just don’t cut it out altogether as it is a good source of nutrients including protein, iron and zinc.
  4. In 2011 the IARC (International Agency on Research on Cancer) declared that mobile phone use is a possible carcinogen (any substance that is an agent directly involved in causing cancer). Shortly afterwards, the Institute of Cancer Research claimed the evidence was increasingly against a link. “The studies are all over the place,” American Cancer Society's medical officer Dr Len Lichtenfeld admits - so there is no need to get rid of your handset just yet.

  5. Currently there is no known research that has found that microwave ovens create cancer-causing substances. “Even if the radio waves they emit are linked with cancer,” says Lichtenfeld, “most people don’t spend anywhere near enough time in the proximity of microwave ovens for this to be a major concern.”

  6. “Right now, most of us think that the evidence shows that coffee does not cause cancer. But it is still on the IARC list,” says Lichtenfeld. In fact, earlier last year, researchers from the US National Cancer Institute and Imperial College, London found that those who drank four to five cups of coffee (caffeinated or decaffeinated) a day reduced risk of developing bowel cancer by 15%. However, the researchers did recommend that further investigation into the link is needed, including study of the specific chemicals in coffee that could be having an effect.
To know more visit http://www.worldcancerday.org/

World Cancer Day (4 February 2013)

Posted by : Stranger
Date :Monday, February 4, 2013
With 0comments

ASP.Net GridView add, edit, delete and update rows

| Sunday, February 3, 2013
Read more »
Download the source code here.

In this article, I am going to explain ASP.Net Data control "GridView" and various methods to perform operations like "Add","Edit","Delete" and "Update" on the data displayed in the GridView rows.

We will be using a Category Table from a local database to demonstrate the above features. Any table with any structure can be used with GridView.

The structure of the table is
  • Id    int
  • Name    varchar(500)
Data in the GridView can be bound in a number of ways using design as well as from code behind.

  1. Design Mode - Drag and Drop GridView control on the aspx from toolbox. Add SqlDataSource control on the aspx page to bind the data into the GridView. Configure SqlDataSource as explained in the following steps:  
    Step 1 : Select Connection string or Create new connection


    Step 2 : Select table or write a custom sql query or procedure

    Step 3 : Click "Advanced" button and check "Generate Insert, Update and Delete Statements"

     
    Step 4 :  Test Query and Click Finish

    The html on the design page should be as follows:

    <asp:SqlDataSource ID="sqlDsListing" runat="server" ConnectionString="<%$ ConnectionStrings:ListingConnectionString %>"
            DeleteCommand="DELETE FROM [Category] WHERE [Id] = @Id" InsertCommand="INSERT INTO [Category] ([Name]) VALUES (@Name)"
            SelectCommand="SELECT * FROM [Category]" UpdateCommand="UPDATE [Category] SET [Name] = @Name  WHERE [Id] = @Id">
            <DeleteParameters>
                <asp:Parameter Name="Id" Type="Int32" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="Name" Type="String" />
                <asp:Parameter Name="Id" Type="Int32" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="Name" Type="String" />
            </InsertParameters>
        </asp:SqlDataSource>
        <asp:GridView ID="gdvListing" runat="server" AllowPaging="True" AllowSorting="True"
            AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" AutoGenerateSelectButton="True"
            DataKeyNames="Id" DataSourceID="sqlDsListing" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True"
                    SortExpression="Id" />
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            </Columns>
        </asp:GridView>

    Please note the properties of GridView in bold text. Above code will automatically handle the "Edit", "Delete" and "Update" operations without any code in the code behind file.



    The resultant page will look like above in the browser.

  2. Code Behind Mode - Add following code snippet to bind the data into GridView in code behind file.

    private void BindGridView()
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.
    ConnectionStrings["ListingConnectionString"].ConnectionString))
            {
                conn.Open();
                using (SqlCommand comm = new SqlCommand("select * from Category", conn))
                {
                    SqlDataAdapter da = new SqlDataAdapter(comm);
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    gdvListing.DataSource = ds;
                    gdvListing.DataBind();
                }
            }
        }
    Add reference of following namespaces in the "using" section of the file.

    using System.Data.SqlClient;
    using System.Configuration;
    using System.Data;
Currently we are using "BoundField" to display data in GridView. But if I need to customize the display of columns or add validations while Editing, then we need to use "TemplateField". In the following section, I will describe TemplateField, ItemTemplate, and EditItemTemplate.

 TemplateField- TemplateField is used to display custom data in the GridView
 ItemTemplate- Content to be displayed in TemplateField
 EditItemTemplate- Content to be displayed in TemplateField in Edit mode.

Another reason of using TemplateField instead of BoundField is that, it is very easy to grab those controls in the codebehind if we user labels or textboxes. In case of the bound field’s we need to check what column it is and need to use index of that cloumn, which is little hard and even in future if we change the column order  we have to change the code too.

We will use code behind data binding model for this section.With TemplateField, the aspx page should look like

<asp:GridView ID="gdvListing" runat="server" AllowPaging="True" AllowSorting="True" ShowFooter="true"
        DataKeyNames="Id" AutoGenerateColumns="False" OnRowCancelingEdit="gdvListing_RowCancelingEdit"
        OnRowCommand="gdvListing_RowCommand" OnRowDeleting="gdvListing_RowDeleting" OnRowEditing="gdvListing_RowEditing"
        OnRowUpdating="gdvListing_RowUpdating">
        <Columns>
            <asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True"
                SortExpression="Id" ItemStyle-Width="10%" />
            <asp:TemplateField HeaderText="Name" SortExpression="Name" ItemStyle-Width="30%">
                <ItemTemplate>
                    <asp:Label runat="server" ID="lblName" Text='<%#Eval("Name") %>' />
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox runat="server" ID="txtName" Text='<%#Eval("Name") %>' />
                    <asp:HiddenField ID='hdnId' runat="server" Value='<%#Eval("Id")%>' />
                    <asp:RequiredFieldValidator runat="server" ID="rfvName" ControlToValidate="txtName"
                        ValidationGroup="1" ErrorMessage="*" />
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox runat="server" ID="txtFooterName" />
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="" ItemStyle-Width="30%">
                <ItemTemplate>
                    <asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
                      
                    <asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
                    <asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:LinkButton ID="btnAddNew" Text="Add New" runat="server" CommandName="AddNew" />
                </FooterTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>


The page in browser will look like this


On clicking the "Edit" button, "gdvListing_RowEditing" event of gridview is fired. Include following code snippet in the event

 protected void gdvListing_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gdvListing.EditIndex = e.NewEditIndex;
        BindGridView();
    }
In the above code snippet as you see GridViewEditEventArgs will give the row number whatever you are editing by NewEditIndex property. So GridView will put the appropriate row into the Edit Mode by assigning row number to its EditIndex property. Then again we have to call that BindGridView() method to bind data for the textboxes.

When "Edit" button is fired, Edit template of button column displays "Update" and Cancel" buttons.


On "Update" button click, "gdvListing_RowUpdating" event is fired which includes following code snippet

protected void gdvListing_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string s = gdvListing.DataKeys[e.RowIndex].Value.ToString();
        TextBox txtName = gdvListing.Rows[e.RowIndex].FindControl("txtName") as TextBox;
        HiddenField hdnId = gdvListing.Rows[e.RowIndex].FindControl("hdnId") as HiddenField;
        String UpdateQuery = string.Format("UPDATE Category
SET Name='{0}' WHERE Id = {1}", txtName.Text, Convert.ToInt32(hdnId.Value));
        gdvListing.EditIndex = -1;
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["ListingConnectionString"].ConnectionString))
        {
            conn.Open();
            using (SqlCommand comm = new SqlCommand(UpdateQuery, conn))
            {
                comm.ExecuteNonQuery();
            }
        }
        BindGridView();
    }

Similarly "Cancel" button click fires "gdvListing_RowCancelingEdit" which includes following code

 protected void gdvListing_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gdvListing.EditIndex = -1;
        BindGridView();
    }

"Delete" button click fires "gdvListing_RowDeleting" and includes following code

protected void gdvListing_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string Id = gdvListing.DataKeys[e.RowIndex].Value.ToString();
        string Query = "delete Category where Id = " + Id;
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["ListingConnectionString"].ConnectionString))
        {
            conn.Open();
            using (SqlCommand comm = new SqlCommand(Query, conn))
            {
                comm.ExecuteNonQuery();
            }
        }
        BindGridView();
    }

Footer template of GridView includes section for adding a new row in the database from the GridView. The "Add New" button click is handled using the "gdvListing_RowCommand" event as follows:

protected void gdvListing_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "AddNew")
        {
            TextBox txtFooterName = (TextBox)gdvListing.FooterRow.FindControl("txtFooterName");
            String InsertQuery = string.Format("INSERT INTO [Category]
([Name]) VALUES('{0}')", txtFooterName.Text);
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["ListingConnectionString"].ConnectionString))
            {
                conn.Open();
                using (SqlCommand comm = new SqlCommand(InsertQuery, conn))
                {
                    comm.ExecuteNonQuery();
                }
            }
            BindGridView();
        }
    }

There is one more method to handle all the above events. All these operations can be handled in "gdvListing_RowCommand" by using different "CommandName" for each button. e.g.

protected void gdvListing_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "AddNew")
        {
            TextBox txtFooterName = (TextBox)gdvListing.FooterRow.FindControl("txtFooterName");
            String InsertQuery = string.Format("INSERT INTO [Category] ([Name]) VALUES('{0}')", txtFooterName.Text);
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ListingConnectionString"].ConnectionString))
            {
                conn.Open();
                using (SqlCommand comm = new SqlCommand(InsertQuery, conn))
                {
                    comm.ExecuteNonQuery();
                }
            }
            BindGridView();
        }
        else if (e.CommandName == "Edit")
        {
            ....
        }
        else if (e.CommandName == "Delete")
        {
            ....
        }
    }

Try and Enjoy Coding!!!

ASP.Net GridView add, edit, delete and update rows

Posted by : Stranger
Date :Sunday, February 3, 2013
With 2comments
Tag : ,
Next Prev
▲Top▲