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

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

Rate me:
Please Sign up or sign in to vote.
4.07/5 (15 votes)
2 Mar 2006CPOL3 min read 93.3K   248   29   14
Editable DataGrid binding - VS 2003 RAD approach (ASP.NET 1.1).

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.

VB
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.

VB
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.

VB
'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.

VB
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.

VB
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)


Written By
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 Pin
Acidbather24-Oct-07 11:26
Acidbather24-Oct-07 11:26 
GeneralRe: I really don't understand what I'm doing wrong Pin
Acidbather24-Oct-07 11:58
Acidbather24-Oct-07 11:58 
QuestionEdting Datagrid in ASP.Net 2.0 Pin
Vijay.c3-Jan-07 19:14
Vijay.c3-Jan-07 19:14 
AnswerRe: Edting Datagrid in ASP.Net 2.0 Pin
Robert R Freeman4-Jan-07 6:44
Robert R Freeman4-Jan-07 6:44 
QuestionQueries (Urgent) Pin
Thilagavathy9-Oct-06 22:49
Thilagavathy9-Oct-06 22:49 
Hi there,

I am new to the .Net technologies.

How to add the dataset to the DatasetGrid1?

I gave like this instead of the "With" block

myData.Fill(DatasetEditGrid1)

myData is the OleDbAdapter object

But the datagrid is not at all displayed.

What would be the problem?

Please help.

Thanks,
Thila
AnswerRe: Queries (Urgent) Pin
Robert R Freeman11-Oct-06 17:51
Robert R Freeman11-Oct-06 17:51 
GeneralDear Godguy, Pin
foozerino912-Apr-06 11:40
foozerino912-Apr-06 11:40 
GeneralRe: Dear Godguy, Pin
Woutervs9-Aug-06 22:40
Woutervs9-Aug-06 22:40 
GeneralRe: Dear Godguy, Pin
Woutervs9-Aug-06 22:52
Woutervs9-Aug-06 22:52 
GeneralRe: Dear Godguy, Pin
Robert R Freeman18-Aug-06 15:02
Robert R Freeman18-Aug-06 15:02 
GeneralRe: Dear Godguy, Pin
Woutervs29-Aug-06 23:07
Woutervs29-Aug-06 23:07 
GeneralRe: Dear Godguy, Pin
Robert R Freeman30-Aug-06 11:40
Robert R Freeman30-Aug-06 11:40 
GeneralRe: Dear Godguy, Pin
Robert R Freeman18-Aug-06 7:00
Robert R Freeman18-Aug-06 7:00 
GeneralRe: Dear Godguy, Pin
Joshua Ramirez19-Oct-07 10:44
Joshua Ramirez19-Oct-07 10:44 

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.