Click here to Skip to main content
15,868,141 members
Articles / Web Development / ASP.NET

Custom DataGridView for Data Management

Rate me:
Please Sign up or sign in to vote.
4.50/5 (8 votes)
8 Dec 2016CPOL9 min read 46K   2.4K   24   29
Custom DataGridView for managing data

Introduction

This article will show users how to use the custom data grid tool for your ASP.NET solution for displaying, sorting, filtering, charting, and extracting data. The custom datagrid tool is very useful for creating and managing data.

Image 1

 

Image 2

Problems the Solution Solves

The default ASP.NET datagrid is very basic and any additional feature you want to add to your application requires lots of programing from paging, filtering, charting, and extracting data. This solution proves several built in features without adding any additional coding. Not only does it simplify and optimize your coding time, it adds rich UI components that give you a vast array of capabilities and functionality. The extended datagrid has built in features for filtering the data, multi selection of records, providing a title, paging, sorting data, chrarting and graphing datasets, and extracting data in a variety of formats without any extra work on your part.

How Does this Help Other Users

This project will help developers by eliminating the need to develop complex coding for adding additional functionality to a datagrid. This will reduce the solution complexity, increase usability, and make your datagrid full of features without having to write several coding features to provide additional functionality.

How Does the Code Work

I have developed an extension class to the DataGridView in Visual Studio. The new DataGridView provides a vast set of features that usually take lots of programming to complete. When using the custom DataGridView, you will be given the ability to filter data in the datagrid, extract data, sort, and page the data with no extra code needing to be written. The walkthrough below explains in detail how to setup the code and get it to work.

Problems Encountered and What I Learned

In developing the solution, I ran into several issues from tracking session state and view state values. Organizing an extended list of features and managing events in the solution. Extending an ASP.NET control is not the simplest task and takes lots of time to test and debug errors. I learned that leveraging the ability to provide dynamic features for extracting, filtering, paging, and ordering data in a datagrid can provide end users with a great usability experience and cut down on the programing time for the developer. Since the solution is packaged in a library, adding updates and features to the library is a snap and will update the entire system without having to update individual controls.  Some issues still exist in the charting feature depending on the chart type selected.  The system depends on the users ability to understand the label and grouping to display different charts.  Updates to the charting sections will continue to be updated.

Background

A few years ago, I wanted to create a tool managing data in a datagrid. Adding the datagrid, paging, filtering and extracting methods was a tedious task and I wanted a control similar to the datagridview that would have all the features built in so I didn't have to code them. I finally ended up building the tool and wanted to share it with the world.

Using the Code

Using the custom tool is very simple. Below is a walkthrough of creating a basic WinForms web application with the custom control.

Open Visual Studio and create a blank web application using Framework 4.5 or greater.

Image 3

Choose a blank WinForms application.

Image 4

Microsoft adds a lot of references by default, but all you need for the demo to start with is:

Image 5

Create a default.aspx page for the application:

Right click your references and add a reference to the CSDRGridView.dll. The CSDRGridView.dll is included in this article.

Image 6

Add the sample TestData.csv file to the solution by adding the existing item. Included is the sample solution provided.

Image 7

Image 8

Add the CSDRGridView to your toolbox of controls by right clicking on the general section of the toolbox and selecting choose items.

Image 9

Browse to the control to add it.

Image 10

From the toolbox, you will see the new gridview control. Open the Default.aspx designer view and drag the gridview onto the page.

Image 11

Go to the code view page and ensure its setup with the columns and references shown in red below:

Image 12

Here is the code that needs to be added if you want to copy and paste it.

HTML
// <%@ Register Assembly="CSDRGridView" Namespace="CSDRGridView.Controls" TagPrefix="cc1" %>
// <%@ Register Assembly="CSDRGridView" Namespace="CSDRGridView.Controls.Fields" TagPrefix="cc1" %>
ASP.NET
<cc1:GridView ID="gvCSDRPagerName" runat="server" CustomPagerSettingsMode="CSDRPager"
    CustomSkin="GreyBlackWhite" DataKeyNames="BusinessEntityID" SkinID="" DefaultSecurity="Admin"
    TableTitle="Sample GridView Data" ShowChartButton="true">
    <PagerSettings Position="TopAndBottom" />
    <EmptyDataTemplate>
        There are no users defined for the table...
    </EmptyDataTemplate>
    <Columns>
        <cc1:BoundField DataField="Title" 
HeaderText="Title" HeaderStyle-Width="60" SortExpression="Title" 
ShowOnExtract="true" />
        <cc1:BoundField DataField="FirstName" 
HeaderText="First Name" HeaderStyle-Width="100" SortExpression="FirstName" 
ShowOnExtract="True" />
        <cc1:BoundField DataField="LastName" 
HeaderText="Last Name" HeaderStyle-Width="100" SortExpression="LastName" 
ShowOnExtract="True" />
        <cc1:BoundField DataField="EmailAddress" 
HeaderText="Email" SortExpression="EmailAddress" ShowOnExtract="True" />
        <cc1:BoundField DataField="AddressLine1" 
HeaderText="Address" SortExpression="AddressLine1" ShowOnExtract="True" />
        <cc1:BoundField DataField="City" 
HeaderText="City" SortExpression="City" ShowOnExtract="True" />
        <cc1:BoundField DataField="StateProvinceName" 
HeaderText="State" SortExpression="StateProvinceName" ShowOnExtract="True" />
        <cc1:BoundField DataField="CountryRegionName" 
HeaderText="Country" SortExpression="CountryRegionName" ShowOnExtract="True" />
        <cc1:BoundField DataField="PostalCode" 
HeaderText="Zip Code" HeaderStyle-Width="60" SortExpression="PostalCode" 
ShowOnExtract="True" />
    </Columns>
</cc1:GridView>

In the Default.aspx.cs code behind page, add the function and set the datasource as shown below:

ASP.NET
//using System;
//using System.Data;
//using System.IO;
//
//namespace SampleGridViewApplication
//{
//    public partial class Default : System.Web.UI.Page
//    {
//        protected void Page_Load(object sender, EventArgs e)
//        {
//            if (!IsPostBack)
//            {
//                gvCSDRPagerName.DataSource = GetXMLDataTable();
//                gvCSDRPagerName.DataBind();
//            }
//        }
//
//        private DataTable GetXMLDataTable()
//        {
//            StreamReader oStreamReader = new StreamReader(Server.MapPath("~/TestData.csv"));
//
//            DataTable oDataTable = null;
//            int RowCount = 0;
//            string[] ColumnNames = null;
//            string[] oStreamDataValues = null;
//            //using while loop read the stream data till end
//            while (!oStreamReader.EndOfStream)
//            {
//                String oStreamRowData = oStreamReader.ReadLine().Trim();
//                if (oStreamRowData.Length > 0)
//                {
//                    oStreamDataValues = oStreamRowData.Split(',');
//                    //Bcoz the first row contains column names, we will populate
//                    //the column name by
//                    //reading the first row and RowCount-0 will be true only once
//                    if (RowCount == 0)
//                    {
//                        RowCount = 1;
//                        ColumnNames = oStreamRowData.Split(',');
//                        oDataTable = new DataTable();
//
//                        //using foreach looping through all the column names
//                        foreach (string csvcolumn in ColumnNames)
//                        {
//                            DataColumn oDataColumn = new DataColumn(csvcolumn.ToUpper(), typeof(string));
//
//                            //setting the default value of empty.string to newly created column
//                            oDataColumn.DefaultValue = string.Empty;
//
//                            //adding the newly created column to the table
//                            oDataTable.Columns.Add(oDataColumn);
//                        }
//                    }
//                    else
//                    {
//                        //creates a new DataRow with the same schema as of the oDataTable            
//                        DataRow oDataRow = oDataTable.NewRow();
//
//                        //using foreach looping through all the column names
//                        for (int i = 0; i < ColumnNames.Length; i++)
//                        {
//                            oDataRow[ColumnNames[i]] = oStreamDataValues[i] == null ? 
//                                     string.Empty : oStreamDataValues[i].ToString();
//                        }
//
//                        //adding the newly created row with data to the oDataTable       
//                        oDataTable.Rows.Add(oDataRow);
//                    }
//                }
//            }
//            //close the oStreamReader object
//            oStreamReader.Close();
//            //release all the resources used by the oStreamReader object
//            oStreamReader.Dispose();
//            return oDataTable;
//        }
//    }
//}

 

In the bin folder of the solution, you need to copy the references shown below.  The extracting features of the custom control are dependent on these DLL libraries.

Image 13

These references have been included in the attached solutions resources directory.

 

Now run the project and use the custom gridview to search, extract and manage your data!

Reference Material

Since the custom gridview is an extension of the Microsoft ASP.NET DataGridView object, you have access to all the built in features plus a variety of new features. You can customize the gridview in a variety of ways such as enabling and disabling extract button. Manage which buttons are visible to the end user. Customize the skin of the gridview as well as several other features. All the features are listed below:

AutoGenerateCheckBoxColumn

(true or false). If you don’t want the auto generated checkbox column and its features, set this value to false and the checkbox column will not be displayed. Default value is true.

ChartWindowAddChartLabelsDropDownFieldSelectText

Allows you to set the Chart windows dropdown list default please select text.

ChartWindowChartFieldValueLabelText

Custom text for the chart field value label

ChartWindowChartGroupByLabelText

Custom text for the chart group by value label

ChartWindowChartLabelText

Custom text for the chart label value label

ChartWindowChartOperationText

Custom text for the chart operation value label

ChartWindowChartTypeText

Custom text for the chart type value label

ChartWindowHeaderText

Custom header text for the chart window

CustomPagerSettingsMode

(CSDRPager, None, PagePreviousNext). There are 3 pager setting modes in the system. The CSDRPager custom pager that shows the mange button, search, and extract features. None which shows no paging, and PagePreviousNext that just shows the paging feature for previous and next.

CustomSkin
Set a custom look and feel to the skin:
  1. BlueWhiteTurquoise
  2. BlueWhiteYellow
  3. GreyBlackWhite
  4. GreyWhiteBlack
  5. None

CustomSkinAlternateBackgroundColorDisabled

(true, false) if you don’t want an alternating background color, set this attribute to true. Default is false.

CheckBoxColumnIndex

The location to display the checkbox column in the datagrid. The default is 0 (first column).

DefaultSecurity

(none, ReadOnly, Admin, Add, Edit, Delete, Export, Search). Users can easily set the security for what they want the user to be able to do by setting the grids default security setting. Default value is none.

EnableSortGraphic

(true or false). If you don’t want the up and down arrow on the sorted column, set this value to false. Default is true.

FilterWindowAddFilterText

Lets you set specific text for the add filter window

FilterWindowAddFilterDropDownFieldSelectText

Lets you set specific text for the add filter window drop down list field select

FilterWindowCurrentFiltersHeaderText

Lets you set specific text for the current filter window header

FilterWindowHeaderText

Lets you set specific text for the add filter window header

OnExportCSV (Event)

Want a custom event when exporting to csv instead of the default, add it here.

OnExportExcel (Event)

Want a custom event when exporting to Excel instead of the default, add it here.

OnExportHTML (Event)

Want a custom event when exporting to HTML instead of the default, add it here.

OnExportPDF (Event)

Want a custom event when exporting to PDF instead of the default, add it here.

OnExportWord (Event)

Want a custom event when exporting to word instead of the default, add it here.

OnItemChecked (Event)

If you want a custom event when an item is checked.

ShowAddButton

(True or False) If you don’t want to see the add button, set this value to false. Default is true.

ShowChartButton (True or False) If you want to see the chart  button, set this value to true. Default is false.

ShowDeleteButton

(True or False) if you don’t want to see the delete button, set this value to false. Default is true.

ShowEditButton

(True or False) if you don’t want to see the edit button, set this value to false. Default is true.

ShowExportCSV

(True or False) if you don’t want to see the csv export button, set this value to false. Default is true.

ShowExportExcel

(True or False) If you don’t want to see the excel export button, set this value to false. Default is true.

ShowExportHTML

(True or False) if you don’t want to see the HTML export button, set this value to false. Default is true.

ShowExportPDF

(True or False) if you don’t want to see the PDF export button, set this value to false. Default is true.

ShowExportWord

(True or False) if you don’t want to see the Word export button, set this value to false. Default is true.

ShowExtractButton

(True or False) if you want to disable the extract feature entirely, you can set this value to false and no extract button will not be displayed. Default is true.

ShowSearchButton

(True or False) if you want to disable the search feature entirely, you can set this value to false and no search button will not be displayed. Default is true.

ShowTableTitle

(True or False) if you don’t want to see the table title at the top of the page set this value to false. Default is true if there is a title value set.

ShowViewButton

(True or False) If you don’t want to see the view item button, set this value to false. Default is true.

ToolTipAddButton

Custom text for the add button tool tip

ToolTipCloseExportWindow

Custom text for the close export window button tool tip

ToolTipCloseFilterWindow

Custom text for the close filter window button tool tip

ToolTipDeleteButton

Custom text for the delete button tool tip

ToolTipEditButton

Custom text for the edit button tool tip

ToolTipExportCSV

Custom text for the export csv button tool tip

ToolTipExportExcel

Custom text for the export excel button tool tip

ToolTipExportHTML

Custom text for the export html button tool tip

ToolTipExportPDF

Custom text for the export PDF button tool tip

ToolTipExportWord

Custom text for the export word button tool tip

ToolTipExtractButton

Custom text for the extract button tool tip

ToolTipFilterWindowDeleteFilterText

Custom text for the filter window delete filter button tool tip

ToolTipFilterWindowSaveFilterOptionText

Custom text for the filter window save filter button tool tip

ToolTipFirstPageButton

Custom text for the paging first button tool tip

ToolTipLastPageButton

Custom text for the paging last button tool tip

ToolTipNextPageButton

Custom text for the paging next page button tool tip

ToolTipPrevPageButton

Custom text for the paging previous page button tool tip

ToolTipRefreshButton

Custom text for the refresh button tool tip

ToolTipSearchButton

Custom text for the refresh button tool tip

ToolTipViewButton

Custom text for the view button tool tip

Example using the system: Here is a YouTube video of how to use the custom control.

History

  • Initial document created
  • Removed need to enter license key
  • Added reference to missing config setting "Custom Skin"
  • Improved debugging for invalid license key error
  • Included DLL resources for extracting feature to work correctly
  • Updated library for setting custom text for the datagrid buttons to support multi languages.
  • Resolved license key bug and removed from requirements.
  • Resolved issue with datasets in master pages.
  • Added Chart.js integration for visualizing datasets.
  • Added ability to save charts an images.
  • Increased demo dataset size to better demo paging and charting fetures.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer CSDR Solutions, LLC
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionAutoGenerateColumns Issue Pin
raihansazal11-Aug-17 18:21
raihansazal11-Aug-17 18:21 
QuestionCustom DataGridView for Data Management databind to SqlDataSource Pin
aliweber22-Nov-16 4:10
aliweber22-Nov-16 4:10 
AnswerRe: Custom DataGridView for Data Management databind to SqlDataSource Pin
haisol22-Nov-16 6:25
professionalhaisol22-Nov-16 6:25 
GeneralRe: Custom DataGridView for Data Management databind to SqlDataSource Pin
aliweber22-Nov-16 21:36
aliweber22-Nov-16 21:36 
GeneralRe: Custom DataGridView for Data Management databind to SqlDataSource Pin
haisol23-Nov-16 3:29
professionalhaisol23-Nov-16 3:29 
QuestionTo haisol Pin
burlakova18-Nov-16 1:38
burlakova18-Nov-16 1:38 
AnswerRe: To haisol Pin
haisol18-Nov-16 3:47
professionalhaisol18-Nov-16 3:47 
QuestionLicense not valid or expired Pin
Member 770477617-Nov-16 20:02
Member 770477617-Nov-16 20:02 
AnswerRe: License not valid or expired Pin
haisol18-Nov-16 3:18
professionalhaisol18-Nov-16 3:18 
AnswerRe: License not valid or expired Pin
haisol18-Nov-16 11:02
professionalhaisol18-Nov-16 11:02 
GeneralRe: License not valid or expired Pin
burlakova19-Nov-16 1:36
burlakova19-Nov-16 1:36 
QuestionLicense is Not Valid or Expired. Pin
burlakova17-Nov-16 18:53
burlakova17-Nov-16 18:53 
AnswerRe: License is Not Valid or Expired. Pin
haisol18-Nov-16 3:40
professionalhaisol18-Nov-16 3:40 
AnswerRe: License is Not Valid or Expired. Pin
haisol18-Nov-16 11:01
professionalhaisol18-Nov-16 11:01 
QuestionMissing Control Property Pin
haisol15-Nov-16 10:00
professionalhaisol15-Nov-16 10:00 
AnswerRe: Missing Control Property Pin
Nelek15-Nov-16 19:27
protectorNelek15-Nov-16 19:27 
QuestionLicesne is not valid or Expired Pin
Yasskier15-Nov-16 8:41
Yasskier15-Nov-16 8:41 
AnswerRe: Licesne is not valid or Expired Pin
haisol15-Nov-16 9:12
professionalhaisol15-Nov-16 9:12 
GeneralRe: Licesne is not valid or Expired Pin
Yasskier15-Nov-16 10:07
Yasskier15-Nov-16 10:07 
GeneralRe: Licesne is not valid or Expired Pin
haisol15-Nov-16 10:18
professionalhaisol15-Nov-16 10:18 
GeneralRe: Licesne is not valid or Expired Pin
Yasskier15-Nov-16 10:29
Yasskier15-Nov-16 10:29 
GeneralRe: License is not valid or Expired Pin
haisol15-Nov-16 10:45
professionalhaisol15-Nov-16 10:45 
GeneralRe: License is not valid or Expired Pin
aliweber16-Nov-16 4:40
aliweber16-Nov-16 4:40 
GeneralRe: License is not valid or Expired Pin
haisol16-Nov-16 6:20
professionalhaisol16-Nov-16 6:20 
AnswerRe: License is not valid or Expired Pin
aliweber16-Nov-16 20:15
aliweber16-Nov-16 20:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.