Click here to Skip to main content
Click here to Skip to main content

Custom editable Datagrid with paging and sorting

, 3 Dec 2003
Rate this:
Please Sign up or sign in to vote.
How to create a grid control for easy editing

Introduction

This article shows you how to create a custom DataGrid with paging, alternate sorting, and is also completely editable

Details

When I was developing some asp.net pages, I lost a lot of time with Datagrids. The code here is to made that work more simple. Only drag the control to the page, complete some properties, point to the methods that controls the updating, deleting and you have a complete editable grid.

[ToolboxData("<{0}:editableElphGrid runat="\""server\">
    </{0}:editableElphGrid>")]
//ParseChildren allow to work with templates inside the custom datagrid
[ParseChildren(true)]
public class editableElphGrid : System.Web.UI.WebControls.DataGrid
{
    /// <span class="code-SummaryComment"><summary>
</span>
    /// Points to the method that returns a datatable with data
    /// Apunta a la funcion q devolvera un dataTable con los datos
    /// <span class="code-SummaryComment"></summary>
</span>
    public delegate DataTable getData();
    /// <span class="code-SummaryComment"><summary>
</span>
    /// Obtain data event 
    /// Evento de obtener datos
    /// <span class="code-SummaryComment"></summary>
</span>
    public event getData GetData;
    /// <span class="code-SummaryComment"><summary>
</span>
    /// Points to method(to update data)
    /// Apunta a un metodo q nos servira para modificar datos
    /// <span class="code-SummaryComment"></summary>
</span>
    public delegate void updateData(int dataKey,DataGridCommandEventArgs e);
    /// <span class="code-SummaryComment"><summary>
</span>
    /// Update data event
    /// <span class="code-SummaryComment"></summary>
</span>
    public event updateData UpdateData;
    /// <span class="code-SummaryComment"><summary>
</span>
    /// Points to method(delete data)
    /// Apunta al metodo q usaremos para eliminar los datos
    /// <span class="code-SummaryComment"></summary>
</span>
    public delegate void deleteData(int dataKey,DataGridCommandEventArgs e);
    /// <span class="code-SummaryComment"><summary>
</span>
    /// delete data event
    /// <span class="code-SummaryComment"></summary>
</span>
    public event deleteData DeleteData; 
    /// <span class="code-SummaryComment"><summary>
</span>
    /// Cancel data
    /// <span class="code-SummaryComment"></summary>
</span>
    public delegate void cancelData(int dataKey,DataGridCommandEventArgs e);
    /// <span class="code-SummaryComment"><summary>
</span>
    /// cancel data event
    /// <span class="code-SummaryComment"></summary>
</span>
    public event cancelData CancelData;
    /// <span class="code-SummaryComment"><summary>
</span>
    /// edit data
    /// <span class="code-SummaryComment"></summary>
</span>
    public delegate void editData(int dataKey,DataGridCommandEventArgs e);
    /// <span class="code-SummaryComment"><summary>
</span>
    /// edit data event
    /// <span class="code-SummaryComment"></summary>
</span>
    public event editData EditData;
    // Note: the params passed on the delegates
    // dataKey: is the DataKey field of the edited/
    // canceled/updated/deleted row
    // e: for work with the cells of the grid
    /// <span class="code-SummaryComment"><summary>
</span>
    /// First sorting field
    /// campo por el q se ordenara en la primera carga
    /// <span class="code-SummaryComment"></summary>
</span>
    private string _cFirst="";
    /// <span class="code-SummaryComment"><summary>
</span>
    /// First sorting field
    /// campo por el q se ordenara en la primera carga
    /// <span class="code-SummaryComment"></summary>
</span>
    public string FirstSortingField
    {
        get
        {return _cFirst;}
        set
        {_cFirst=value;}
    }
    // Inicializamos el grid
    protected override void OnInit(EventArgs e)
    {
        //paginacion=true
        this.AllowPaging=true;
        //ordenacion=true
        this.AllowSorting=true;
        //evento cambio de pagina
        //ADD the events
        this.PageIndexChanged+=new DataGridPageChangedEventHandler(
              cPage_elphGrid);
        //evento ordenar
        this.SortCommand+=new DataGridSortCommandEventHandler(
               Order_elphGrid);
        //evento de cargar datos
        this.Load+=new EventHandler(elphGrid_Load);
        this.EditCommand+=new DataGridCommandEventHandler(Edit_elphGrid);
        this.CancelCommand+=new DataGridCommandEventHandler(Cancel_elphGrid);
        this.DeleteCommand+=new DataGridCommandEventHandler(Delete_elphGrid);
        this.UpdateCommand+=new DataGridCommandEventHandler(Update_elphGrid);
        //clear the columns
        //limpiamos las columnas
        this.Columns.Clear();
        //create the editComandColumn an deleteColumn
        //creamos las columnas de editar i eliminar
        EditCommandColumn col=new EditCommandColumn();
        col.ButtonType=ButtonColumnType.LinkButton;
        col.CancelText="Cancel";
        col.EditText="Edit";
        col.UpdateText="Update";
        this.Columns.Add(col);
        ButtonColumn delCol=new ButtonColumn();
        delCol.CommandName="Delete";
        delCol.ButtonType=ButtonColumnType.LinkButton;
        delCol.Text="Delete";
        this.Columns.Add(delCol);
    }
    private void elphGrid_Load(object sender, EventArgs e)
    {
        if(!this.Page.IsPostBack)
        {
            //changed Session object for Viewstate
            if(this.AllowSorting&&this._cFirst!="")
                this.ViewState.Add("_orderBy",this._cFirst);
            this.ViewState.Add("_orderType","ASC");
            this.DataSource = CreateDataSet();
            this.DataBind();
        }
    }
    private void cPage_elphGrid(object sender, 
             DataGridPageChangedEventArgs e)
    {
        //PAging
        this.CurrentPageIndex = e.NewPageIndex;
        this.DataSource = CreateDataSet();
        this.DataBind();
    }
    private ICollection CreateDataSet() 
    {
        //this.ObtenerDatos call a external function that return data
        DataTable dt=this.GetData();
        if(this.AllowSorting&&this.ViewState["_orderBy"]!=null)
        {
            //sort the grid
            if(this.ViewState["_orderType"].ToString() == "ASC")
                dt.DefaultView.Sort=(string)
                   this.ViewState["_orderBy"].ToString()+" ASC";
            else if(this.ViewState["_orderType"].ToString()=="DESC")
                dt.DefaultView.Sort=(string)this.ViewState["_orderBy"]+
                          " DESC";
        }
        return dt.DefaultView;
    }
    public void Order_elphGrid(object sender, DataGridSortCommandEventArgs e) 
    { 
        this.ViewState["_orderBy"]=(string)e.SortExpression;
        if(this.ViewState["_orderType"].ToString()=="ASC")
            this.ViewState["_orderType"]="DESC";
        else if(this.ViewState["_orderType"].ToString()=="DESC")
            this.ViewState["_orderType"]="ASC";
        this.DataSource = CreateDataSet();
        this.DataBind(); 
    }
    public void Edit_elphGrid(object sender, 
           System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
        int id=Convert.ToInt32(this.DataKeys[e.Item.ItemIndex]);
        this.EditData(id,e);
        this.EditItemIndex=e.Item.ItemIndex;
        this.DataSource = CreateDataSet();
        this.DataBind();
    }
    public void Delete_elphGrid(object sender, 
          System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
        int id=Convert.ToInt32(this.DataKeys[e.Item.ItemIndex]);
        this.DeleteData(id,e);
        this.EditItemIndex=-1;
        this.DataSource = CreateDataSet();
        this.DataBind();
    }
    public void Update_elphGrid(object sender, 
           System.Web.UI.WebControls.DataGridCommandEventArgs e) 
    {
        int id=Convert.ToInt32(this.DataKeys[e.Item.ItemIndex]);
        this.UpdateData(id,e);
        this.EditItemIndex=-1;
        this.DataSource = CreateDataSet();
        this.DataBind();
    }
    public void Cancel_elphGrid(object sender, 
            System.Web.UI.WebControls.DataGridCommandEventArgs e) 
    {
        int id=Convert.ToInt32(this.DataKeys[e.Item.ItemIndex]);
        this.CancelData(id,e);
        this.EditItemIndex=-1;
        this.DataSource = CreateDataSet();
        this.DataBind();
    }
}

Well, now add the control on a page, and then you must fill the fields .

DataKeyField: That is the key field of the table, the unique identifier of a row. I put because I use that on Database actions, like delete a specific row etc.

And on the tab of Events :- GetData, CancelData, EditData and DeleteData.

Finally you should have something like this.

On the aspx page:

<cc1:editableElphGrid id="EditableElphGrid1" runat="server" 
    DataKeyField="intId"></cc1:editableElphGrid>

On the code behind

protected elphControls.editableElphGrid EditableElphGrid1;
   
private void InitializeComponent()
{    
 this.EditableElphGrid1.DeleteData += 
   new elphControls.editableElphGrid.eliminarDatos(this.del);
 this.EditableElphGrid1.GetData += 
   new elphControls.editableElphGrid.obtenerDatos(this.obt);
this.EditableElphGrid1.EditData += 
   new elphControls.editableElphGrid.editarDatos(this.edit);
 this.EditableElphGrid1.UpdateData += 
   new elphControls.editableElphGrid.actualizarDatos(this.act);
 this.EditableElphGrid1.CancelData += 
   new elphControls.editableElphGrid.cancelarDatos(this.cncl);
 this.Load += new System.EventHandler(this.Page_Load);
}
private System.Data.DataTable obt()
{
OleDbConnection conn=new OleDbConnection(
    "Provider=Microsoft.Jet.OLEDB.4.0;Data source=E:\\bdProves.mdb");
 OleDbDataAdapter adapter=new OleDbDataAdapter("select * from tabla",conn);
 adapter.SelectCommand.CommandType=CommandType.Text;
 conn.Open();
 DataSet ds=new DataSet();
 adapter.Fill(ds,"aa");
 conn.Close();
 conn.Dispose();
 return ds.Tables["aa"];
}
private void edit(int dataKey, 
    System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
//here the logic asociated with edit comand... if you have
}
private void del(int dataKey, 
    System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
 //here the logic asociated with delete comand
}
private void cncl(int dataKey, 
    System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
 //here the logic asociated with Cancel comand
}
private void act(int dataKey, 
    System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
 //here the logic asociated with update comand
}

Update

Changed the session to save the sorting params for a viewstate, now you can have two grids on the same page. Also Changed the declaration of the first sorting field, now this isn't necessary. Thanks to Zanoza.

Conclusion

I think that this grid is a good base to customize a datagrid. Hope it could be useful. All comments about this are welcomed.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author


Comments and Discussions

 
Questionevents firing twice Pinmembermojkurs9-Feb-06 16:39 
AnswerRe: events firing twice Pinmembermojkurs9-Feb-06 17:54 
GeneralGetting text from edit/update Pinmemberbkerr1-Nov-05 20:25 
GeneralDataGrid : column width Pinmemberthanchu2-Oct-05 19:22 
GeneralProgramming Style Tips PinmemberPinhead_Me18-Oct-04 10:36 
When naming your objects, its best to use a coding style that provides additional context to your application logic and structure.
 
Example:
 
for a DataGrid
DataGrid dgProducts; //Note that just by looking at that object one can easily deduce it is a Datagrid.
 
Also, events that are associated with that DataGrid can be coded like this:
 
Edit_gdProducts(...);
Update_gpProducts(...);
 
also, using del, cncl, act method names adds little context, it would be best to spell out method names for clarity. Leaving out author names in objects is also recommended and rarely, if ever, practiced by non-egotistical programmers.

GeneralRe: Programming Style Tips PinmemberKlom Dark23-Jan-06 5:43 
GeneralRe: Programming Style Tips PinmemberPinhead_Me23-Jan-06 8:39 
GeneralRe: Programming Style Tips Pinmembermtone28-Jan-07 5:32 
Generallogic asociated with update comand PinmemberHamish Ahern18-Oct-04 2:31 
QuestionCan you write VB.NET? PinmemberHamish Ahern18-Oct-04 1:40 
GeneralHola PinmemberFernando Finelli21-Jul-04 8:04 
GeneralControl LoadViewState PinmemberRruedi3-Jul-04 7:11 
General@ Register Pinmemberfsdkjfskl17-Mar-04 5:02 
QuestionHow to use the source file? Pinmemberdeny0123-Jan-04 4:46 
QuestionHow do I had non autogenerate columns ? PinmemberErnest Bariq25-Dec-03 23:20 
AnswerRe: How do I had non autogenerate columns ? PinmemberErnest Bariq30-Dec-03 6:51 
GeneralError PinmemberGeorgeMar10-Dec-03 6:31 
GeneralRe: Error PinmemberElph10-Dec-03 11:33 
GeneralRe: Error PinmemberGeorgeMar11-Dec-03 0:14 
GeneralRe: Error PinsussAnonymous11-Dec-03 2:26 
GeneralRe: Error PinmemberGeorgeMar11-Dec-03 4:05 
GeneralProblem with first loading PinmemberZanoza5-Dec-03 5:27 
GeneralRe: Problem with first loading PinmemberElph5-Dec-03 8:56 
GeneralThow! Spanish! PinmemberJonathan de Halleux4-Dec-03 21:15 
GeneralRe: Thow! Spanish! PinmemberElph4-Dec-03 21:33 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.1411023.1 | Last Updated 4 Dec 2003
Article Copyright 2003 by Elph
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid