banner



How To Create Custom Gridview Control In Asp Net

#1

Reputation: 448

  • View blog
  • Posts: 1,504
  • Joined: 28-April 09

Posted 05 February 2011 - 11:37 AM

I still consider myself fairly new to ASP.net overall, but one thing I've noticed is that the default server controls do not always provide the best in functionality or appearance. The control that annoys me most though is the GridView control. It works well when you are only dealing with a handful of pages, but I've had projects with over a thousand pages and the page controls that come with the GridView just aren't designed to deal with that much data, at least not in a user friendly manner. After a few times of implementing custom paging on the GridView I decided it was time to just go ahead and create my own control with the custom paging built in to save myself the headache of having to do it again. Now, I didn't want to create a completely new type of grid control from the ground up so decided to just inherit from the GridView control and go from there.

A few notes before I get into the code, I created this using C# in Visual Studio 2010(.Net 4.0), but it should work fine in Visual Studio 2008(.Net 3.5) as well. Start out by creating a new Class Library Project. Now you can add a new item to your project, I chose ASP.Net Server Control as that loads the basic shell of a server control for you, but you can also just add a normal class and go from there as well. You probably want to name the class file something meaningful, like CustomGridView.cs, or MyGrid.cs, or AGridViewWithACustomPagerBuiltIntoIt.cs, or whatever else makes sense to you. You may, or may not, need to add a reference to System.Design to your project, I did. Here is where you can find some information on adding and removing references to your project as that is not in the scope of this tutorial.

To get started here are the usings that were necessary to build the project.

Spoiler


using System; using System.ComponentModel; using System.Web.UI; using System.Web.UI.Design.WebControls; using System.Web.UI.WebControls;                

Now if you chose ASP.Net Server Control as the new item then go ahead and delete the Text Property and the Render Method that were created as we will not be dealing with those. Ok, so the next thing we want to do is name our class and tell it that we want to inherit from the GridView control. We also need to add a couple of attributes to the class. We will add a designer attribute so Visual Studio will know how to render the control during design time. As this control inherits from GridView we can just use the GridViewDesigner class instead of creating our own. We will also add a ToolBoxData attribute, this attribute tells visual studio how to create the tag for the control when it's moved from the toolbox onto your .aspx page.

Spoiler


[Designer(typeof(GridViewDesigner))] [ToolboxData("<{0}:NewGrid runat=server></{0}:NewGrid>")] public class NewGrid : GridView {  }                

Now we can get on to the actual creation of the new pager control. For this we're going to use four controls: 3 Button controls, and a TextBox control.

Spoiler


public class NewGrid : GridView {     private TextBox txtCurrentPage;     private Button btnPrevious;     private Button btnChangePage;     private Button btnNext;  }                

I added a property to allow the user the option of enabling the custom pager or to use the default pager control. To persist the value of this property we need to make sure its value is stored to ViewState. This property is not necessary to the operation of the control, but if you choose to not include it you will need to be sure to remove the references to it in other parts of the code.

Spoiler


                  [Description("Enable the custom pager when paging is allowed.")]     [Category("behavior")]     public bool EnableCustomPaging     {         get         {             object temp = ViewState["EnableCustomPaging"];             return temp == null ? false : (bool)temp;         }         set { ViewState["EnableCustomPaging"] = value; }     }                

Since we are creating a pager control we will make use of the GridView's InitializePager method. We do this by overriding the method and adding our custom logic to it. In this case we just want to see if the user has chosen to use the custom pager and if so to load our custom pager controls.

Spoiler


                  protected override void InitializePager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource)     {         if (EnableCustomPaging)             InitializeCustomPager(row, columnSpan, pagedDataSource);              // method we will be creating this method         else             base.InitializePager(row, columnSpan, pagedDataSource);     }                

Now we can go ahead and initialize our pager controls and add them to the Pager Row. This step includes setting all of the properties for out controls, such as the test, events and any other properties you would like to set.

Spoiler


                  private void InitializeCustomPager(GridViewRow row,                                     int columnSpan,                                     PagedDataSource pagedDataSource)     {         btnChangePage = new Button();         btnNext = new Button();         btnPrevious = new Button();         txtCurrentPage = new TextBox();          btnChangePage.Text = "Go";         btnChangePage.Click += new EventHandler(btnChangePage_Click);          btnNext.Text = ">>";         btnNext.Click += new EventHandler(btnNext_Click);          btnPrevious.Text = "<<";         btnPrevious.Click += new EventHandler(btnPrevious_Click);          txtCurrentPage = new TextBox();         txtCurrentPage.Width = new Unit(3, UnitType.Em);         txtCurrentPage.TextChanged += new EventHandler(txtCurrentPage_TextChanged);         // Set the text of the textbox to the current page index + 1         txtCurrentPage.Text = (pagedDataSource.CurrentPageIndex + 1).ToString();         txtCurrentPage.AutoPostBack = true;          TableCell cell = new TableCell();         cell.ColumnSpan = columnSpan;          cell.Controls.Add(btnPrevious);         // Just to let the user know this number represents the current page         cell.Controls.Add(new LiteralControl("Page: "));         cell.Controls.Add(txtCurrentPage);         // Tells the user the total number of pages         cell.Controls.Add(new LiteralControl(" of " + pagedDataSource.PageCount));         cell.Controls.Add(btnChangePage);         cell.Controls.Add(btnNext);                  row.Controls.Add(cell);                

Simple enough so far huh, well if you're expecting it to get more difficult then I'm sorry to say you're going to be disappointed. All that's left is to handle our pager control events and this control will be ready for use. I'm not going to go into a lot of detail on each individual event as the logic is fairly straightforward, but I will put in some comments to kind of walk through it.

Spoiler


                  private int? ChangePage(string strIndex)     {         try         {             // attempt to convert user input to an integer             int index = ((Convert.ToInt32(strIndex)) - 1);              // if index is less than 0, set index to 0             if (index < 0) index = 0;             // if index is greater than or equal to PageCount,             // set index to PageCount - 1             if (index >= PageCount) index = PageCount - 1;              return index;         }         catch         {             // if user input could not be converted to an             // integer then we return null             return null;         }     }       void txtCurrentPage_TextChanged(object sender, EventArgs e)     {         // set index equal to return value of ChangePage method         // if index is not null then set PageIndex equal to index's value         int? index = ChangePage(txtCurrentPage.Text);         if (index.HasValue) this.PageIndex = index.Value;     }      void btnPrevious_Click(object sender, EventArgs e)     {         // if the page index is greater than zero then          // reduce the page index by one         if (this.PageIndex > 0)         {             this.PageIndex--;             this.DataBind();         }     }      void btnNext_Click(object sender, EventArgs e)     {         // if the page index is less than or equal to the page count         // then increase the page index by one         if (this.PageIndex <= this.PageCount)         {             this.PageIndex++;             this.DataBind();         }     }      void btnChangePage_Click(object sender, EventArgs e)     {         // set index equal to return value of ChangePage method         // if index is not null then set PageIndex equal to index's value         int? index = ChangePage(txtCurrentPage.Text);         if (index.HasValue) this.PageIndex = index.Value;     }                

And that's the final step. You should now be able to build the control. To use it in another project now just add a reference to the .dll that was created and you can then add the control to your toolbox.

Adding Items To The ToolBox

Attached Image


Is This A Good Question/Topic? 1

  • +

#2 spanjam User is offline

  • New D.I.C Head

Reputation: 0

  • View blog
  • Posts: 1
  • Joined: 05-April 13

Posted 05 April 2013 - 10:08 AM

Excelent article, has served as a base to start enhancing a control. Thanks

How To Create Custom Gridview Control In Asp Net

Source: https://www.dreamincode.net/forums/topic/214220-creating-a-custom-gridview-control-with-its-own-custom-paging-control/

Posted by: hamiltonwathre.blogspot.com

0 Response to "How To Create Custom Gridview Control In Asp Net"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel