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

Editable DataGrid Binding - VS 2003 RAD approach (ASP.NET 1.1) - EditGrid

By , 2 Mar 2006
Rate this:
Please Sign up or sign in to vote.

Sample image

Introduction

This article outlines the fastest and simplest way to develop an ASP.NET 1.1 editable DataGrid using Visual Studio 2003.

Making an EditGrid

This article assumes a DataSet has been added to your page from the toolbox or an adapter. See http://vsnetdatabinding.blogspot.com/ for info on adding a DataSet and Adapter to your page.

1. Drag/Drop a DataGrid

Drag a DataGrid from the Toolbox onto your form.

Drag Drop the Datagrid

2. Set the Datasource

Right click the DataGrid and click Property Builder.

Right-Click Property Builder

Set the DataSource, DataMember, and DataKey fields to the DataSet on your page.

Set the Datasource

3. Add an EditCommandColumn

Switch to the Columns tab. Add the Edit, Update, and Cancel button columns.

Add Edit Column

4. (Optional) Create TemplateColumns for custom editors

If you need any non-label textbox controls, then you will need to create template columns. In this example, we have a boolean column, so we will add a checkbox control template. In order to keep the template column from being duplicated automatically, unselect the Create Columns Automatically checkbox and add every column to the Selected Columns list. Select the column needing a custom editor and click Convert this column into a Template Column. Click Ok to exit the Property Builder.

TemplateColumn

Right click on the grid and select Edit Template. Select the template column you just converted.

Sample screenshot

Delete the textbox in the EditItemTemplate. Drag/drop the appropriate control into the EditItemTemplate from the Toolbox. Bind the control's Value property to the appropriate Container/Data Item/Column. In this example, the CheckBox's Checked property is bound to the ClockedIn column.

Bind Template Checkbox

If you also desire a non-editable display other than text, then follow the above procedure for the ItemTemplate. In this example, the Label is replaced with a CheckBox. The CheckBox's Enabled property is then set to false to disallow edits.

To exit Template Edit mode, right click on the grid and select End Template Editing.

End Template Editing

Let's Write Some Code

5. Fill/Cache/Retrieve your dataset

Do this on the page load. On no postback, you will fill and cache the dataset. On postback, you will retrieve the cached dataset.

Private Sub Page_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load

    If Not Me.IsPostBack Then

        'Fill values into your dataset.
        'If using a database data source, replace this "With" block 
    'with your adapter.fill
        With Me.DatasetEditGrid1.EditGrid
            .AddEditGridRow("Robert", "Site 1", True)
            .AddEditGridRow("Bill", "Site 2", False)
            .AddEditGridRow("Joe", "Site1", True)
        End With

        'Cache dataset. (You can also use session to cache)
        Me.ViewState("DatasetEditGrid1") = Me.DatasetEditGrid1
    Else
        'Point to the cached dataset.
        Me.DatasetEditGrid1 = CType(Me.ViewState("DatasetEditGrid1"), _
     DatasetEditGrid)
    End If
End Sub

6. Create an EditCommand handler

Switch to the code-behind and add an EditCommand handler for the DataGrid.

Edit Command Handler

Set the EditItemIndex here.

Private Sub DataGrid1_EditCommand(ByVal source As Object, _
    ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) _
    Handles DataGrid1.EditCommand

    Me.DataGrid1.EditItemIndex = e.Item.ItemIndex
End Sub

7. Create a CancelCommand handler

Reset the EditItemIndex (-1 denotes no EditItem).

Private Sub DataGrid1_CancelCommand(ByVal source As Object, _
        ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) _
        Handles DataGrid1.CancelCommand
    Me.DataGrid1.EditItemIndex = -1
End Sub

8. Create an UpdateCommand handler

Copy the generic SetDatasetValuesFromGrid reverse binding code. You should add a new ElseIf section for each type of control you will be using in the grid. This instance handles TextBoxes and CheckBoxes.

'Generic Code to do Reverse binding from a DataGridItem cell to its
'corresponding DataTable item.
Private Sub SetDatasetValuesFromGrid(ByVal DataTable As DataTable, _
        ByVal DataTableColumnName As String, _
        ByVal DataGridItem As DataGridItem, _
        ByVal DataGridCellIndex As Integer)

    For Each control As Control In DataGridItem.Cells(DataGridCellIndex).Controls
        If TypeOf control Is CheckBox Then
            Me.DatasetEditGrid1.EditGrid(DataGridItem.DataSetIndex)(DataTableColumnName) _
        = CType(control, CheckBox).Checked
            Exit For
        ElseIf TypeOf control Is TextBox Then
            Me.DatasetEditGrid1.EditGrid(DataGridItem.DataSetIndex)(DataTableColumnName) _
        = CType(control, TextBox).Text
            Exit For
        End If
    Next
End Sub

Call the SetDatasetValuesFromGrid for each cell in the edit row. Use an enum to correlate the dataset column names to the grid's column indexes. Save the dataset to your datasource using an adapter.update (not done in this example). Reset the EditItemIndex.

Private Sub DataGrid1_UpdateCommand(ByVal source As Object, _
    ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) _
    Handles DataGrid1.UpdateCommand
        
UpdateDatasetFromGrid()
    Me.DataGrid1.EditItemIndex = -1
End Sub

'Relate the Dataset's Column Names to the Column Index in the Datagrid
Private Enum DatasetColumnNameToGridColumnIndex
    Name = 1
    Location = 2
    ClockedIn = 3
End Enum

'Reverse bind from the datagrid to the dataset.
Private Sub UpdateDatasetFromGrid()
    For Each ColName As DatasetColumnNameToGridColumnIndex _
In System.Enum.GetValues(GetType(DatasetColumnNameToGridColumnIndex))
        SetDatasetValuesFromGrid(Me.DatasetEditGrid1.EditGrid, ColName.ToString, _
    Me.DataGrid1.Items(Me.DataGrid1.EditItemIndex), ColName)
    Next

    'Normally you would save (adapter.update) to the database here.
End Sub

9. Bind the crid (Very important!)

Bind the grid in the PreRender event to ensure the most recent dataset changes are reflected in the grid.

Private Sub DataGrid1_PreRender(ByVal sender As Object, _
            ByVal e As System.EventArgs) Handles DataGrid1.PreRender
    'Bind the Grid.
    Me.DataGrid1.DataBind()
End Sub

Conclusion

After following these steps, you can run the application and test the results. Please comment on anything that needs further clarification, or with any questions on implementing this. Also, please provide suggestions before rating the article less than a 5.

Enjoy!

License

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

About the Author

Robert R Freeman
Chief Technology Officer Kiefer Consulting
United States United States
Sacramento, CA based Senior .Net and SharePoint Solution Architect for Kiefer Consulting
(1-800-794-1928)
B.S. in Mathematics from UCDavis
.NET Wizard - Experts-Exchange
MCSD, MCTS: MOSS 2007 Config
 
Some of the bigger questions:
1. What is the meaning of my life?
To satisfy the purpose of your creator(s). (Meaning must derive from purpose. Those who create you, give you meaning.)
 
2. Who is my creator?
Ultimately, God is your creator. God designed and created the universe and everything in it. You and others in your life can also be a part of your creation, overriding or furthering God's purpose.
 
3. What is God's purpose for me?
To love and be loved by your creator and others and to enjoy the life you've been given.
This can be distinguished two ways.
a. Use your built in common sense (morality/feelings)
b. Use the creator's handbook. Fortunately our creator did not abandon us. He is with us now and even lived and died as one of us. Check out his biography in "The Bible"
 
Note on free-will vs. predetermination:
God exists outside the constraints of time. He exists at every point in time simultaneously and knew of your birth and every decision you will/have made. But this does not mean God predetermined any of it. Pre and post are time related concepts that do not apply to God. God always has been and always will be. He determines our universe to exist, gives it the parameters of natural law, and allows us to make our own way through it (free-will). Note that these are all present tense, it would be more appropriate to use past, present, and future tense combined. God's purpose is for us to love him and one another. But a prerequisite of love is the free-will to love. So even though God wants us to love him/others, he can not ensure it. He can, however, help us if we allow him to. A miracle is God modifying natural parameters in response to human will.

Comments and Discussions

 
GeneralI really don't understand what I'm doing wrong PinmemberAcidbather24-Oct-07 11:26 
GeneralRe: I really don't understand what I'm doing wrong PinmemberAcidbather24-Oct-07 11:58 
Of course as is usually the case, about 5 minutes after I posted this I realized my problem. Also as is usually the case, it was a very simple issue, though it still doesn't make sense to me.
 
I had to mark the columns that I didn't want to appear as text boxes as being Read Only. This doesn't make sense to me becuase it seems that the only columns that should appear as text boxes (or whatever control you decide upon) should be those that you set as being template columns.
 
Anyway, thanks for the great article and any further input.
QuestionEdting Datagrid in ASP.Net 2.0 PinmemberVijay.c3-Jan-07 19:14 
AnswerRe: Edting Datagrid in ASP.Net 2.0 PinmemberRobert R Freeman4-Jan-07 6:44 
QuestionQueries (Urgent) PinmemberThilagavathy9-Oct-06 22:49 
AnswerRe: Queries (Urgent) PinmemberRobert R Freeman11-Oct-06 17:51 
GeneralDear Godguy, Pinmemberfoozerino912-Apr-06 11:40 
GeneralRe: Dear Godguy, PinmemberWoutervs9-Aug-06 22:40 
GeneralRe: Dear Godguy, PinmemberWoutervs9-Aug-06 22:52 
GeneralRe: Dear Godguy, PinmemberRobert R Freeman18-Aug-06 15:02 
GeneralRe: Dear Godguy, PinmemberWoutervs29-Aug-06 23:07 
GeneralRe: Dear Godguy, PinmemberRobert R Freeman30-Aug-06 11:40 
GeneralRe: Dear Godguy, PinmemberRobert R Freeman18-Aug-06 7:00 
GeneralRe: Dear Godguy, PinmemberJoshua Ramirez19-Oct-07 10:44 

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 | Mobile
Web04 | 2.8.140415.2 | Last Updated 2 Mar 2006
Article Copyright 2006 by Robert R Freeman
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid