Sunday, July 31, 2011

Creating Dynamically GridView with custom Template Field in C#

GridView – big brother of data grid, one of the mostly used controls for its effective use of representing data. Smile Ok ok, let us get to the topic now, to start with ……………...

TemplateField Class

This example shows how to create a GridView dynamically and add desired columns. I have used this in asp.net page and I had to add the GridView in the aspx page, rest all in the code behind file.  Before starting did some R&D and found some information on the available Column Fields from in MSDN and thought to share a bit of it here.

 

Column Fields

Each column in the GridView control is represented by a DataControlField object. By default, the AutoGenerateColumns property is set to true, which creates an AutoGeneratedField object for each field in the data source. Each field is then rendered as a column in the GridView control in the order that each field appears in the data source.

You can also manually control which column fields appear in the GridView control by setting the AutoGenerateColumns property to false and then defining your own column field collection. Different column field types determine the behavior of the columns in the control. The following table lists the different column field types that can be used.

Column field type

Description

BoundField

Displays the value of a field in a data source. This is the default column type of the GridView control.

ButtonField

Displays a command button for each item in the GridView control. This enables you to create a column of custom button controls, such as the Add or the Remove button.

CheckBoxField

Displays a check box for each item in the GridView control. This column field type is commonly used to display fields with a Boolean value.

CommandField

Displays predefined command buttons to perform select, edit, or delete operations.

HyperLinkField

Displays the value of a field in a data source as a hyperlink. This column field type enables you to bind a second field to the hyperlink's URL.

ImageField

Displays an image for each item in the GridView control.

TemplateField

Displays user-defined content for each item in the GridView control according to a specified template. This column field type enables you to create a custom column field.

 

To define a column field collection declaratively, first add opening and closing <Columns> tags between the opening and closing tags of the GridView control. Next, list the column fields that you want to include between the opening and closing <Columns> tags. The columns specified are added to the Columns collection in the order listed. The Columns collection stores all the column fields in the control and enables you to programmatically manage the column fields in the GridView control.

 

Explicitly declared column fields can be displayed in combination with automatically generated column fields. When both are used, explicitly declared column fields are rendered first, followed by the automatically generated column fields.

Now, after all these information, I am sure now know what are the column types you can use in a GridView. In this article I will only deal with the Template Column and that too in code base.  In precise, it can be done by implementing ITemplate interface in System.Web.UI namespace. In this article, I will explain the construction of dynamic GridView  control by building dynamic template columns.

The Template class

public class MyGridViewTemplate : ITemplate

{

    private DataControlRowType templateType;

    private string columnName;

 

    public MyGridViewTemplate(DataControlRowType type, string colname)

    {

        templateType = type;

        columnName = colname;

    }

 

    public void InstantiateIn(System.Web.UI.Control container)

    {

        // Create the content for the different row types.

        switch (templateType)

        {

            case DataControlRowType.Header:

                // Create the controls to put in the header section and set their properties.

                Literal lc = new Literal();

                lc.Text = "<B>" + columnName + "</B>";

                // Add the controls to the Controls collection of the container.

                container.Controls.Add(lc);

                break;

            case DataControlRowType.DataRow:

                // Create the controls to put in a data row section and set their properties.

                Label firstName = new Label();

                Label lastName = new Label();

                Literal spacer = new Literal();

                spacer.Text = " ";

 

                // To support data binding, register the event-handling methods

                // to perform the data binding. Each control needs its own event handler.

                firstName.DataBinding += new EventHandler(this.FirstName_DataBinding);

                lastName.DataBinding += new EventHandler(this.LastName_DataBinding);

 

                // Add the controls to the Controls collection of the container.

                container.Controls.Add(firstName);

                container.Controls.Add(spacer);

                container.Controls.Add(lastName);

                break;

 

            // Insert cases to create the content for the other row types, if desired.

 

            default:

                // Insert code to handle unexpected values.

                break;

        }

    }

 

    private void FirstName_DataBinding(Object sender, EventArgs e)

    {

        // Get the Label control to bind the value. The Label control

        // is contained in the object that raised the DataBinding event (the sender parameter).

        Label l = (Label)sender;

 

        // Get the GridViewRow object that contains the Label control. 

        GridViewRow row = (GridViewRow)l.NamingContainer;

 

        // Get the field value from the GridViewRow object and assign it to the Text property of the Label control.

        l.Text = DataBinder.Eval(row.DataItem, "Links").ToString();

      

    }

 

    private void LastName_DataBinding(Object sender, EventArgs e)

    {

        // Get the Label control to bind the value. The Label control

        // is contained in the object that raised the DataBinding event (the sender parameter).

        Label l = (Label)sender;

 

        // Get the GridViewRow object that contains the Label control.

        GridViewRow row = (GridViewRow)l.NamingContainer;

 

        // Get the field value from the GridViewRow object and assign it to the Text property of the Label control.

        l.Text = DataBinder.Eval(row.DataItem, "Links1").ToString();

    }

}

 

And now we will see the page class. aspx.cs

public partial class GridViews_GridView1 : System.Web.UI.Page

{

    #region Controls  + Variables

    #endregion

 

    protected void Page_Load(object sender, EventArgs e)

    {

       

        ////Populate Data

        DataTable dt = new DataTable();

        dt.Columns.Add("Links");

        dt.Columns.Add("Links1");

        DataRow dr;

        for (int i = 1; i < 10; i++)

        {

            dr = dt.NewRow();

            dr["Links"] = "A" + i;

            dr["Links1"] = "B" + i;

            dt.Rows.Add(dr);

            dt.AcceptChanges();

        }

        ////Grid view

        // The field columns need to be created only when the page is first loaded. 

        if (!IsPostBack)

        {

            gvTest.AutoGenerateColumns = false;

            // Dynamically create field columns to display the desired

            // fields from the data source. Create a TemplateField object 

            // to display an author's first and last name.

            TemplateField customField = new TemplateField();

            // Create the dynamic templates and assign them to 

            // the appropriate template property.

            customField.HeaderTemplate = new MyGridViewTemplate(DataControlRowType.Header, "Test Name");

            customField.ItemTemplate = new MyGridViewTemplate(DataControlRowType.DataRow, "");

            // Add the field column to the Columns collection of the GridView control.

            this.gvTest.Columns.Add(customField);

 

            BoundField boundField = new BoundField();

            boundField.HeaderText = "Bug ID";

            boundField.DataField = "Links";

            this.gvTest.Columns.Add(boundField);

 

            gvTest.DataSource = dt;

            gvTest.DataBind();

           

        }

    }

}
Hope few simple copy paste and the code should run…. Smile


If you have a more elegant solution – please post a comment… I’ll be happy to hear.

...HaPpY CoDiNg

Partha (Aurum)

 

Creating Dynamically GridView  with custom Template Field in C#

 

TemplateField in GridView

Creating GridView in C# by Code

Implementing ITemplate for custom TemplateField in GridView

Monday, July 18, 2011

How to use DiskPart.exe

I had to increase my SharePoint VM, know why?

Need to restore a production site backup. A personal opinion, it is not advisable to restore production backups which are larger in size say more than 10GB. In my case it was a nightmare with 2 days of effort, all gone in vain. If you have SQL Server 2005 Express, then forget about restore, the DB will only allow not more than 4gb of data, heck!!!!

 

Getting back to the topic, the options I exercised is to increase the size of the disk space. I increased the volume D:

The DiskPart.exe is an efficient tool to increase the volume size

 

Steps to get this done:

1.     Go to command prompt and write diskpart.exe

 

Microsoft Windows [Version 5.2.3790]

(C) Copyright 1985-2003 Microsoft Corp.

 

C:\Documents and Settings\sp_admin>diskpart.exe

 

Microsoft DiskPart version 5.2.3790.3959

Copyright (C) 1999-2001 Microsoft Corporation.

On computer: ALCVMSPD004

 

2.       If you need to see the what all activity we can perform with diskpart.exe then, just make a mistake and it will let you know all it can do for you. I wrote a wrong command and all options were displayed, see easy option to know more he he he Smile

DISKPART> slect volume

 

Microsoft DiskPart version 5.2.3790.3959

 

ADD         - Add a mirror to a simple volume.

ACTIVE      - Marks the current basic partition as active.

ASSIGN      - Assign a drive letter or mount point to the selected volume.

AUTOMOUNT   - Enables and disables automatic mounting of basic volumes.

BREAK       - Break a mirror set.

CLEAN       - Clear the configuration information, or all information, off the disk.

CONVERT     - Converts between different disk formats.

CREATE      - Create a volume or partition.

DELETE      - Delete an object.

DETAIL      - Provide details about an object.

ATTRIBUTES  - Manipulate volume attributes.

EXIT        - Exit DiskPart

EXTEND      - Extend a volume.

GPT         - Assigns attributes to the selected GPT partition.

HELP        - Prints a list of commands.

IMPORT      - Imports a disk group.

INACTIVE    - Marks the current basic partition as inactive.

LIST        - Prints out a list of objects.

ONLINE      - Online a disk that is currently marked as offline.

REM         - Does nothing. Used to comment scripts.

REMOVE      - Remove a drive letter or mount point assignment.

REPAIR      - Repairs a RAID-5 volume with a failed member.

RESCAN      - Rescan the computer looking for disks and volumes.

RETAIN      - Place a retained partition under a simple volume.

SELECT      - Move the focus to an object.

 

3.       To start from beginning, let us do it once more

 

DISKPART> exit

 

Leaving DiskPart...

 

C:\Documents and Settings\sp_admin>diskpart.exe

 

Microsoft DiskPart version 5.2.3790.3959

Copyright (C) 1999-2001 Microsoft Corporation.

On computer: ALCVMSPD004

 

4.       See the listing of the volumes available

 

DISKPART> list volume

 

  Volume ###  Ltr  Label        Fs     Type        Size     Status     Info

  ----------  ---  -----------  -----  ----------  -------  ---------  --------

  Volume 0     E   VSSD1        UDF    CD-ROM       103 MB  Healthy

  Volume 1     C                NTFS   Partition     40 GB  Healthy    System

  Volume 2     D   DATA         NTFS   Partition     80 GB  Healthy

 

5.       In my case I have increase the D: so select the appropriate volume you want.

DISKPART> select volume 2

 

Volume 2 is the selected volume.

6.       Now is the time to extend it,  give the size you want to allocate.

DISKPART> extend size = 100

 

DiskPart successfully extended the volume.

 

DISKPART>

 

 

Please post a comment if you have other ways of doing this same thing… I’ll be happy to hear.
If this helps...... then please share......

HaPpY CoDiNg... (Aurum)