Saturday, September 18, 2010

ASP.NET: CREATING GRIDVIEW WITH BOUND AND TEMPLATE FIELDS

As a developer I have face issue of slipping the code from mind which has drove me nuts some time for 2 to 3 hours and most of the time it happened when it came to write code for GridView control. I don't use GridView that frequently because Repeater control is their which faster and lighter; However, at time a requirement arise when there is no way out.
So I decide to blog the code over the internet for my and others convenience.
As compared to Repeater control GridView control is heavy... but it provides lots of other features which are help full in rapid application development for instance paging and sorting.
In this post I am goanna demonstrate a very simple GridView example which has two bound columns (BoundField) and one template column (TemplateFdeld).  I will bind this GridView with generic list.
Step 1:
First of all we need to create a GridView. In the following HTML I just have created a GridView by writing following line.  AutoGenerateColumns property is telling that no need to generate columns automatically, if I turn this property true GrivView look in the data source assigned to it and creates columns according to that data source. 
<asp:GridView runat="server" AutoGenerateColumns="False">
.......
</asp:GridView>
This step is equal to the step of dropping GridView control on the page from toolbar in designer mode.
Step 2: 
After adding GridView control to the aspx page now it's time to create columns. We can define different types of columns depending upon our requirement.
BoundField - If we want data to be shown as it is in the data source for instance ProductId from Product's data source or Student Id. We just need to provide DataField and GridView takes care of binding this field. When using BoundField GridView treats all the data as string or it convert all the data to its string representation for instance: Boolean data will change to true or false that is what string representation is.
TemplateField - If we want to show different data on different conditions we can use TemplateField for which we need to assign the value manually. TemplateField allow developer to add control of his choice in the column.
Developers have the liberty of adding several other types of fields in GridView for example ImageField,  CheckBoxField, HyperLinkField, CommandField, and ButtonField but in order to keep this example simple I am only using BoundFiels amd TemplateField.
All the columns developer adds in the GridView goes between column tag and adds in the GridView's column collection.
<Columns>
......
</Columns>
To add columns in the GridView add following piece of code between GridView Starting and Ending tags.
<Columns>
    <asp:BoundField DataField="StudentId" HeaderText="Student Id" />
    <asp:BoundField DataField="StudentName" HeaderText="Student Name" />
    TemplateField Visible="true" HeaderText="has Qualify For Scholarship">
        <ItemTemplate>   
            <asp:CheckBox id="chkQualifyForScholarship" runat="server" Checked='' />   
        </ItemTemplate>
    TemplateField>
</Columns>
In te above code I have used this <!--Convert.ToBoolean(Eval("QualifyForScholarship"))--> notation. This is asp code, any code comes between <% and %> is asp code and runs on the server. What I have dont hear is I typecast the field in the data source to Boolean and assign this Boolean value to Checked property of ChechBox control. This cause CheckBox control to show checkbox checked on true and un checked on false. Eval() is the method to fetch value from data source when writing inline asp code.
 Step 3:
EmptyDataTemplate - We can also specify if there are no records in the data source how empty row will be shown with some user-friendly message by using EmptyDataTemplate rather than using label and showing message in it after checking data source whether it does have records or not.
<EmptyDataTemplate>
......
</EmptyDataTemplate>
There are several other templates available in GridView out of the box but they are not in the scope of this article. I'll discuss them in upcoming posts.
Following is the complete HTML of GridView which I have discussed. All you need to do is copy and paste in the .aspx page.
<table>
     <tr>
        <td>
            <asp:GridView runat="server" AutoGenerateColumns="False">
                <Columns>
                    <asp:BoundField DataField="StudentId" HeaderText="Student Id" />
                    <asp:BoundField DataField="StudentName" HeaderText="Student Name" />
                    <asp:TemplateField Visible="true" HeaderText="has Qualify For Scholarship">
                        <ItemTemplate>
                            <asp:CheckBox id="chkQualifyForScholarship" runat="server" Checked='' />
                        </ItemTemplate>     
                    </asp:TemplateField>
                </Columns>
                <EmptyDataTemplate>
                    no student found.
                </EmptyDataTemplate>
            </asp:GridView>
        </td>
    </tr>
</table>
We have done with HTML, now it's time to write CS code.
Step 4: 
In this example I am goanna use generic list of custom developed class. So first we need to create class named Student with three variables named StudentId (data type: Int32), StudentName (data type: String), QualifyForScholarship (data type: Boolean).
NOTE: Remember to create properties otherwise at the time of binding GridView will raise en exception.
public class Student
{
    private Int32 studentId;
    public Int32 StudentId
    {
        get { return studentId; }
        set { studentId = value; }
    }      
private String studentName;
    public String StudentName
    {  
         get { return studentName; }  
         set { studentName = value; }
    }   
private Boolean qualifyForScholarship;
    public Boolean QualifyForScholarship
    {
        get { return qualifyForScholarship; }
        set { qualifyForScholarship = value; }
    }
}
Step 5: 
As we have done with creating business entity now it's time to utilize it. All we need to do is create an object of typed list List<Student> and add objects of Student type in this list. Following is the code for get this thing done. Add the following code in load event of the aspx page.

List lstStudent = null;
lstStudent = new List();
Student objStudent = null;

objStudent = new Student();
objStudent.StudentId = 1;
objStudent.StudentName = "Salman Abbass";
objStudent.QualifyForScholarship = false;
lstStudent.Add(objStudent);

objStudent = new Student();
objStudent.StudentId = 2;
objStudent.StudentName = "Asad Abbass";
objStudent.QualifyForScholarship = true;
lstStudent.Add(objStudent);

objStudent = new Student();
objStudent.StudentId = 3;
objStudent.StudentName = "Kashif Abbass";
objStudent.QualifyForScholarship = true;
lstStudent.Add(objStudent);

objStudent = new Student();
objStudent.StudentId = 4;
objStudent.StudentName = "Ali Raza";
objStudent.QualifyForScholarship = false;
lstStudent.Add(objStudent);

objStudent = new Student();
objStudent.StudentId = 5;
objStudent.StudentName = "Taqi Raza";
objStudent.QualifyForScholarship = false;
lstStudent.Add(objStudent);

dgStudent.Data source = lstStudent;
dgStudent.DataBind();
This is all we need to do. Run the code and enjoy, have a nice day :).

1 comment:

  1. This is a nice article..
    Its very easy to understand ..
    And this article is using to learn something about it..

    c#, dot.net, php tutorial

    Thanks a lot..!

    ReplyDelete