Recent Posts

Sunday, January 18, 2009

How to bind an object in Grid View in visual studio .Net 2005 and handle Paging?

This article will be very helpful for the beginners and intermediate asp net programmer. This will show the easiest possible way of binding the asp net gridview in Asp net 2.0. This also explains how easily we can use the paging gridview feature of the asp net grid view without including any additional statements in the sql select query because sometimes there can be instances where the programmer is not allowed to change the sql query but they can be responsible for displaying data on the web application . So this technique will solve all the questions that are not solved by other postings seen on the web.

While doing this and prior to this post i have noted all the problems I faced and I will explain some of the related problems in this article.

This article will try to answer following questions:

How to use ASP Net Required field validator control?

How to display loading image in Asp Net 2.0 using AJAX ?

How to use ajax extensions in master and detail pages in Asp net 2.0 ?

How to solve "Element 'ScriptManager' is not a known element" error in Asp net 2.0 ?

How to handle "sys" is undefined error while using scriptmanager in Asp net 2.0 ?

Learn asp net "How to develop asp net 2.0 ajax web application with gridview?" with asp net 2.0 free source code.


Ok Now Lets Start................


Step 1



(Note: This article assumes you have installed Microsoft visual studio .net 2005 if not you can go to Microsoft express editions download page )

First open Microsoft Visual Studio 2005 and go to File --> New -->Website

Now select Asp.Net Web Site and give the path of your development site to be and
choose the language on which you want to code.

(Note: This article is written in c# so this will be talking about C# code samples in this article)

Step 2 (Adding Master and child pages)

Add one master page and name it main.Master and one child page and name it Default.aspx

(note you will see current default.aspx so just delete the current one and add the new one and select master page while adding it)

You can see How to work with Asp.net 2.0 Master pages? for more detail information on how to work with master pages.

Step 3 (Adding gridview)

Now add a gridview in your default.aspx in "asp:content" or just drag and drop in design view and name appropriately. 
In this example i have given ID="grdData" and set AllowPaging="true".
see code below:


(The style of the grid can be changed from the design view by right clicking on the grid view and AutoFormat and then select the desired style for the gridview.)


Now we have got a detail page consisting of a gridview with id "grdData".
Now we need to get the data from the database to feed in the grid. For this reason i have used two classes clsDBobj.cs and DBClass.cs which is responsible for getting the data from the database.

You can write your data access classes yourself of if you want to get full detail on how to retrieve data from database you can see my post "How to retrieve data from sql server database from .net application?"

Step 4 (clsPerson)

Now lets add a class in the project and name it clsPerson and save it. This will be the object of person and includes all the getters and setters for the person class.

Lets assume Person has ID, Name, Address, Phone No fields.
And you need to write the following code in this class :

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// 
/// Summary description for clsPerson
/// 

public class clsPerson
{
public clsPerson()
{
//
// TODO: Add constructor logic here
//
}

    private int _id ;
    private string _name;
    private string _address;
    private string _phoneNo;

    public int ID
    {
        get
        { return _id; }
        set
        { _id = value; }
    }

    public string Name
    {
        get
        {
            return _name;  
        }
        set
        {
            _name = value;
        }
    }

    public string Address
    {
        get
        { return _address; }
        set
        { _address = value; }
    }

    public string PhoneNo
    {
        get
        { return _phoneNo; }
        set
        { _phoneNo = value; }
    }
}




In the above code these are just the getters and setters of the clsPerson.
Getter and setter in normal language are the properties of the class.

Step 5 (DBClass)

Similarly add a new class and name it DBClass. This will be the class where we will be writing the data retrieval query and this class will be mainly responsible for returning collection of clsPerson which in turn can be used as data source in grid view.

Now just paste the following two functions in code in this class:


public List clsperson> GetPerson1(int maximumRows, int startRowIndex)
    {
        DataSet ds;
        string str = "";
        clsDBObj objDB = new clsDBObj();
        clsPerson obj;

        str = "Select * from Suppliers";

        ds = objDB.getDataSet(str);
        DataTable dt = ds.Tables[0];

        int currentIndex = startRowIndex;
        int itemsRead = 0;
        int totalRecords = dt.Rows.Count;
        List clsperson> persons = new List clsperson>();

        while (itemsRead < maximumRows && currentIndex < totalRecords)         {             obj = new clsPerson();             obj.ID = Convert.ToInt32(dt.Rows[currentIndex]["SupplierID"].ToString());             obj.Name = dt.Rows[currentIndex]["ContactName"].ToString();             obj.Address = dt.Rows[currentIndex]["Address"].ToString();             obj.PhoneNo = dt.Rows[currentIndex]["Phone"].ToString();             persons.Add(obj);             itemsRead++;             currentIndex++;         }         return persons;              }




public static clsPerson[] GetPerson(int maximumRows, int startRowIndex)
  {
      ArrayList ar = new ArrayList();
      DataSet ds;
      string str = "";
      clsDBObj objDB = new clsDBObj();
      clsPerson obj;

      str = "Select * from Suppliers";

      ds = objDB.getDataSet(str);

      DataTable dt = ds.Tables[0];

      int currentIndex = startRowIndex;
      int itemsRead = 0;
      int totalRecords = dt.Rows.Count;
      
      while (itemsRead < maximumRows &&               currentIndex < totalRecords)       {           obj = new clsPerson();           obj.ID = Convert.ToInt32(dt.Rows[currentIndex]["SupplierID"].ToString());           obj.Name = dt.Rows[currentIndex]["ContactName"].ToString();           obj.Address = dt.Rows[currentIndex]["Address"].ToString();           obj.PhoneNo = dt.Rows[currentIndex]["Phone"].ToString();                                          ar.Add(obj);           itemsRead++;           currentIndex++;       }       obj = new clsPerson();       return (clsPerson[])ar.ToArray(obj.GetType());         }  



Now in above code you can see I am using the class clsDBObj to connect to the sql server database and to get dataset of records. Get more detail about this class and know about secure database connection and easy transaction handling in .net Applications.

Similarly in above code we can notice that there are two functions GetPerson which returns the collection of clsPerson and GetPerson1 that returns the list of clsPerson. We can use any of the functions. I am just showing this to explain clearly on how we can return the object collection in different ways in .net.
But in my example I will be using GetPerson and the query will extract the supplier information from Northwind SQL Server sample database.


Step 6 (Bind Grid View)

Now lets go to code behind of default.aspx page ie: "default.aspx.cs" and bind the grid with the data.

Just paste the following code in your default.aspx.cs and call the function BindGridonLoad() on page load and run the application.

clsPerson[] prns;
   private void BindGridonLoad()
   {       
       prns = DBClass.GetPerson(int.MaxValue, 0);        
       // we are calling GetPerson class straight from 
       // the class because GetPerson is a static function

       grdData.DataSource = prns;
       grdData.DataBind();   
   }


Now at this stage your application should run with data in the grid if it doesn't just go back and check your steps.
And now when you press the paging on the grid it would give error saying "The GridView 'grdData' fired event PageIndexChanging which wasn't handled." That means we haven't written our code for the paging of our grid so for that lets go to the next step.

Step 7 (Page Index Changing code)

Lets go to Default.aspx Design page and select the gridview and open the properties of the gridview or press F4 to see the properties and press the events button to see all the events of gridview see below image:



Then double click on PageIndexChanging event and paste the follwoing code in the code behind default.aspx.vb:

protected void grdData_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {   
        prns = DBClass.GetPerson(int.MaxValue, 0);       

        grdData.PageIndex = e.NewPageIndex;
        grdData.DataSource = prns;
        grdData.DataBind();    
    }


In the above code you can just find the difference is griddata.pageindex =
e.newpageIndex. I have included the max value and startRow in the GetPerson function but haven't used it here because i am just showing that there are both ways of doing this.

Now we can run the application and see our grid loads data and its paging is working properly. But we can see that columns are not in the right order and even header text is not what we desired so in next step we will try to bind the individual column of the grid and display the desired header text of each column.

Step 8 (Bind individual Column of grid view)

Lets go to the Default.aspx source page and in the gridview set
AutoGenerateColumns="False".

Also bind the individual columns in the gridview as shown in the image below and
try running the application and you can see the formatted gridvew as desired.



Now we have completed binding the data in grid view now in next steps i would show how to use ajax (Asynchronous JavaScript and XML) while loading the grid and show loading image.

Step 9 (Use Ajax in Asp.net application)

First add a loading.gif image in the project to show the application is loading.
"Download the animated loading images from AJAX Load Image"

Frist download Asp.net AJAX 1.0 and install it into your pc else .net will show error if we try to use its controls.

Lets go to the Default.aspx page and just place the scriptManger and Updatepanel
add contenttemplate inside update panel and close contenttemplate and updatepanel just before the asp:content tag as shown in the figure below:



Now in the image you can see there is red underline in most of the Ajax components that means visual studio 2005 is not understanding the ajax component. And we can see the following error message : "Element 'ScriptManager' is not a known element. This can occur if there is a compilation error in the Web Site"

I googled it and found an article on Asp.net Ajax Error post.

And the above post explains this might be because i have not installed Visual Studio 2005 Service Pack 1 . Download Visual Studio 2005 Service Pack 1

After Visual studio 2005 service pack 1 is installed all the errors are removed from the code and it seems now visual studio 2005 understands all the Ajax components.

Then below asp:Gridview just put the updateprogress code as below to show loading progress image:


Ok now run the application and see the ajax effect ... " opps " we can see no ajax effect but there we see error on the page and the error is " 'Sys' is undefined ". Now see the next step to solve this error:

Step 10 ( How to solve 'Sys' is undefined error? )

This is explained clearly in the post 'Sys' is undefined - ASP.NET AJAX Error solved

Now after changing the web.config file now your site is Ajax enabled and has grid view with paging.

You can download How to bind an object in Grid View in visual studio .Net 2005 Tutorial file here.

Please feel free to comment


Read more!

Azo Web Sphere: How To Post Code Snippets in Blogger Post

Azo Web Sphere: How To Post Code Snippets in Blogger Post: "Upload the SyntaxHighlighter"


Read more!

Wednesday, January 7, 2009

" Failed to access IIS metabase error " while launching ASP .Net 2.0 Application

This error typically occurs when you install IIS after you have asp.net installed. It is a very simple fix.

Copy and paste this into the Run Command from the Start Menu.
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i

This will reinstall asp.net for use with IIS and in most cases fixes the error stated above.

My MCP: Failed to access IIS metabase.


Read more!

Thursday, January 1, 2009

How to include signature in your reply email in Gmail?

I am a big user of Gmail and i liked it from long time. But there are few things that Gmail didn't provided their users. Like including the signature in your reply email and also including HTML email signatures.

You can check out my post How to include HTML email signature in Gmail? or How to publish your website link in your email signature in Gmail?.

But now finally gmail supports signature in reply email and that is very useful.

To make use of this feature we have to go to Settings and then click on Labs tab.

Then scroll down and you can find Signature tweaks. Now enable that option and scroll down the page and save the changes.

Ok from now your reply emails will include signature.


Read more!

How to provide your web site link in your email signature ? step by step process

I was thinking of providing my blog link in my email signatures so that all the people who see my email know that i have a blog so they and even I can benefit from that.

I just tried to append html tags but gmail does not allow html email signatures. SO I went through many articles in google and came to know the trick see image below:


Even though i found out how to include HTML email signatures in G mail, I have to spend lot of time finding out what to do next and where to find the stuffs. And thought if it would be difficult for me a computer professional to find out the stuffs then how it would feel to the normal computer users? will they be able to do this? I don't think they would be able to experiment and find the exact way out.

Therefore i have included steps to insert HTML signature in Gmail.

Step 1

Note this only works for Mozilla Firefox Browser.
If you don't use Firefox then download Firefox Browser and install it in your computer. It is one of the safest and efficient browsers.

Step 2

Now after installing Mozilla Firefox browser open the firefox browser then download and install Greasemonkey script into your Firefox browser by clicking the link in this line.

Note: Firefox might ask you to register just complete the registration process and login before installation.

Step 3

Now after installing Greasemonkey script you need to install the script to include your email signature in your gmail so for this you need to download the script called Gmail HTML signatures script and install it in Firefox browser.

Note: Firefox might ask you to register just complete the registration process and login before installation.

Step 4

Now you can login to your gmail account normally as you do and go to compose mail now you will see some new items on your compose mail page which looks similar to the image shown below:


Here in this image you can see there are few new controls that you can see.

Step 5

Now press edit signature button and you can see Signature html code:

Just write down your details and html code. Now here you can even include the picutre links so that it would display pictures in your email signature.

Ok now if you don't know how to write html code you can check the tutorial but for some minor stuff i will write you a sample code below:

Here i am writing this code all inclosed by (') you need to remove (') before using the code below.

My signature starts as follows (you can just change the text and paste it in your gmail and it should work):



Thanks, '<'br/'>'
Prateek Regmi '<'br/'>''<'br/'>'

URL:'<'a href="http://www.rprateek.blogspot.com" target="_new" '>' Blog For Programmers '<'/a'>''<'br/'>''<'br/'>'


Step 6

After getting the desired signature just click save signature and your signature is saved. Now all your new emails that you compose the signature is included in your email and your email will look more cooler if you give the links to your pictures located online or give the link to animated thanks picture instead of just writing thanks.



Read more!