Click here to Skip to main content
15,879,535 members
Articles / Desktop Programming / Windows Forms
Article

DataGridView with Detail Edit Form - VS 2005

Rate me:
Please Sign up or sign in to vote.
4.36/5 (30 votes)
24 Jul 2007CPOL4 min read 341.5K   11.1K   132   50
How to create a DataGridView with an associated Detail Edit Form using a strongly typed dataset data layer.

Sample Image

Introduction

This article is a tutorial on how to create a WinForms selectable datagridview with a separate Form for editing detail row data using a strongly typed DataSet data layer. We will use Visual Studio 2005 and .NET 2.0.

Background

Creating an editable datagrid is a very straightforward way to edit a datagrid's values, but sometimes a separate editable Form/UserControl is desired (increased flexibility, more detail, etc.). This example will load the editable fields and lookups with the grid on Form load. This will keep us from having to synchronize and manage separate instances of similar data and will reduce round trips to the database. When dealing with lots of records, you would want to implement a where filter in your query. We will include a Save button on the Edit form. The Save button could just as easily be implemented on the main form. The edit form could also be changed to a UserControl to display on the main form instead of a popup.

Walkthrough

1. Add a DataSource (Strongly typed dataset)

  • Create a new Windows Forms Project and create two forms, Orders and Order.
  • Open Orders in Design View.
  • Click on Add New Datasource in the Data Sources Window.

    Add Data Source

  • Choose Database as the Datasource Type.
  • Create a New Connection.
  • Select Microsoft SQL Server (SqlClient) as the Data Source.
  • Enter the location and login credentials for the Northwind Database.
  • Click Next till you get to Choose Your Database Objects.
  • Select OrderID, CustomerID, and EmployeeID from the Orders table, CustomerID, CompanyName, and ContactName from the Customers table, and EmployeeID, LastName,FirstName and Title from the Employees table as below:

    All Tables

    Image 4 Image 5Image 6

  • Click Finish.

    Note

    This automatically creates the NorthwindDataSet strongly typed dataset with related tables/tableAdapters.

    Image 7

  • Change the CustomerID and EmployeeID columns to ComboBoxes in the Data Sources Window.

    Image 8

2. Create the DataGridView

  • Drag the Orders table from the Data Sources Window onto the Orders form.

    Image 9

  • This will create a NorthWindDataSet instance, a BindingSource, and a BindingNavigator.
  • Delete the BindingNavigator.

    Image 10

  • Click the DataGridView's "Smart Tag" to open the DataGridView Tasks Window.

    Image 11

  • Disable Editing, Deleting, and Adding. Then dock in parent container.
  • Click Edit Columns...Change the CustomerID and EmployeeID columns to DataGridViewComboBoxColumn ColumnTypes.

    DataGridViewComboBoxColumn

  • Bind the Datasource, DisplayMember, and ValueMember properties for the Customer and Employee columns.

    CustomersDataSource

    EmployeesDataSource

    Customer Column

    Employee Column

    Note

    Selecting the DataSources from the Project Data Sources node automatically creates the BindingSources and TableAdapters for the Form.

  • Change the DisplayStyle to Nothing for both columns since these will be read-only.

3. Create the Edit Form

  • Open the Order form in design view.
  • Change the NorthwindDataSet.Orders table in the DataSources Window from DataGridView to Details.

    Image 17

  • Drag the detail table from the DataSources Window onto the Order form. This will create the 3 controls on the form as well as the DataSet, BindingSource, TableAdapter, and BindingNavigator.
  • Delete the BindingNavigator.
  • Drop a Button control on the form and rename it ButtonSave.
  • Click each ComboBoxes' "Smart Tag" to edit the DataSource, DisplayMember, SelectedValue, and ValueMember properties as we did earlier with the GridViewComboBoxColumns.
    You must check the Use data bound items option to edit these values.

    Smart Tag

    Data Source Selected Value

  • This will create BindingSource and TableAdapter components on the form for the Employees and Customers tables.
  • Delete the corresponding TableAdapters (Not the OrdersTableAdapter) since we will be filling these tables from the Orders form.
  • Set the DataBindings.Text property to None since we're now binding to the SelectedValue property.

    Text DataBinding

4. Instantiate the Edit Form

  • Create a Sub New() in the Edit Form.

    Order Sub New

  • Double-click the Save button in design mode to create a click event handler.
  • Use the following code (fix any naming differences):

    VB.NET
    Private Sub Orders_FormClosing(ByVal sender As Object, _
            ByVal e As System.Windows.Forms.FormClosingEventArgs) _
            Handles Me.FormClosing
        'Reject any changes that were not saved.
        Me.NorthwindDataSet.Orders(Me.OrdersBindingSource.Position)._
                                RejectChanges()
    End Sub
    
    Private Sub ButtonSave_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles ButtonSave.Click
        'Update the database and close.
        Me.Validate()
        Me.OrdersBindingSource.EndEdit()
        If Not Me.OrdersTableAdapter.Update(Me.NorthwindDataset.Orders) > 0 _
        Then
            MsgBox("No records were updated.")
        End If
        Me.Close()
    End Sub
    
    Public Sub New(ByVal nwDataSet As NorthwindDataSet, _
                        ByVal position As Integer)
        ' This call is required by the Windows Form Designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
        ' We will specify the DataSet from the DataGrid form here
        Me.NorthwindDataset = nwDataSet
        Me.OrdersBindingSource.DataSource = Me.NorthwindDataSet
        Me.CustomersBindingSource.DataSource = Me.NorthwindDataSet
        Me.EmployeesBindingSource.DataSource = Me.NorthwindDataSet
        Me.OrdersBindingSource.Position = position
    End Sub
    
    Private Sub Order_Load(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles MyBase.Load
    
        'Do not refill. You could optionally refresh this record or
        'access additional database columns by creating another query
        'with a primary key parameter in the table adapter.
        'Me.OrdersTableAdapter.Fill(Me.nwDataSet.Orders)
    End Sub

    Note

    In Sub New, we will pass in the dataset created and filled with the grid. We then point the local NorthwindDataSet variable to the existing dataset. This does not change the properties already set in InitializeComponent for the DataSet, so we must reconfigure the other elements on the form to point to the existing DataSet. Fortunately, the BindingSources provide abstraction. We need only reset the 3 BindingSources' DataSource properties. We then set the BindingSource position so the form knows which record to edit.

  • On Save click, we will save the changes and exit.
  • Finally on form close, we undo any changes that were not saved, because the dataset is shared with the grid.

5. Code the DataGridView Double-click event

  • Open the Orders form in code view.
  • Create a RowHeaderMouseDoubleClick event handler.

    Grid Double Click

  • Create a FormClosing event handler.
  • Use the following code (fix any naming differences):

    VB.NET
    Private Sub Orders_FormClosing(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.FormClosingEventArgs) _
        Handles Me.FormClosing
        Me.OrdersDataGridView.Dispose()
    End Sub
    
    Private Sub Orders_Load(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the
        ''NorthwindDataSet.Employees' table.
        'You can move, or remove it, as needed.
        Me.EmployeesTableAdapter.Fill(Me.NorthwindDataSet.Employees)
        'TODO: This line of code loads data into the
        ''NorthwindDataSet.Customers' table.
        'You can move, or remove it, as needed.
        Me.CustomersTableAdapter.Fill(Me.NorthwindDataSet.Customers)
        'TODO: This line of code loads data into the
        ''NorthwindDataSet.Orders' table. 
        'You can move, or remove it, as needed.
        Me.OrdersTableAdapter.Fill(Me.NorthwindDataSet.Orders)
    End Sub
    
    Private Sub OrdersDataGridView_RowHeaderMouseDoubleClick_
        (ByVal sender As Object, ByVal e _
        As System.Windows.Forms.DataGridViewCellMouseEventArgs) _
        Handles OrdersDataGridView.RowHeaderMouseDoubleClick
        If Me.OrdersDataGridView.SelectedRows.Count > 0 Then
            Dim editForm As New Order(Me.NorthwindDataSet, _
            Me.NorthwindDataSet.Orders.Rows.IndexOf_
            (CType(CType(Me.OrdersDataGridView.SelectedRows(0)._
            DataBoundItem, DataRowView).Row, NorthwindDataSet.OrdersRow)))
            editForm.Show()
        End If
    End Sub

Note

The DataSet is filled on form load. The tableadapter fill statements were created by configuring the BindingSource. We have to dispose of the grid before the form closes to avoid possible DataErrors from the GridViewComboBoxColumns.

The Double-click event instantiates the detail edit form, passing in the DataSet and the position. The position is found by tracking the selected row back to its row instance in the order table, then finding the index of that row in the dataset.

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

 
GeneralRe: can not update, cursor stack after value in combo changed Pin
Robert R Freeman29-Nov-07 12:51
Robert R Freeman29-Nov-07 12:51 
GeneralRe: can not update, cursor stack after value in combo changed Pin
CTekse30-Nov-07 10:57
CTekse30-Nov-07 10:57 
QuestionHow to add new rows? Pin
CTekse12-Nov-07 0:17
CTekse12-Nov-07 0:17 
AnswerRe: How to add new rows? Pin
Robert R Freeman14-Nov-07 8:06
Robert R Freeman14-Nov-07 8:06 
QuestionNeed some clairifaction Pin
rudemusik14-Oct-07 16:30
rudemusik14-Oct-07 16:30 
AnswerRe: Need some clairifaction Pin
Robert R Freeman14-Oct-07 19:06
Robert R Freeman14-Oct-07 19:06 
GeneralRe: Need some clairifaction Pin
rudemusik15-Oct-07 17:54
rudemusik15-Oct-07 17:54 
GeneralRe: Need some clairifaction Pin
rudemusik16-Oct-07 16:35
rudemusik16-Oct-07 16:35 
Hi Robert!

I have one more question. Where does the order_ID get passed. If I double click on Order ID "7", how am I passing that so I see the details of that order id 7. Normally I would have a SP with @OrderID, but I don't see how you are doing that.

In my case, I'm just showing 4 or 5 colmns from one table, that say has 12. The in the details, I just want to show all 12. But I want to pass the order_id, so I show the right details of the order.

Thanks!

RudyBig Grin | :-D
GeneralRe: Need some clairifaction Pin
rudemusik17-Oct-07 7:56
rudemusik17-Oct-07 7:56 
QuestionQuestions Pin
smh17-Oct-07 6:30
smh17-Oct-07 6:30 
AnswerRe: Questions Pin
Robert R Freeman8-Oct-07 6:23
Robert R Freeman8-Oct-07 6:23 
GeneralRe: Questions Pin
smh18-Oct-07 10:05
smh18-Oct-07 10:05 
GeneralC# Code Pin
Keith Cuulm18-Sep-07 14:30
Keith Cuulm18-Sep-07 14:30 
GeneralAtheist & PropertyGrid Pin
Marcus Deecke3-Aug-07 13:03
Marcus Deecke3-Aug-07 13:03 
GeneralRe: Atheist & PropertyGrid Pin
Robert R Freeman6-Aug-07 10:31
Robert R Freeman6-Aug-07 10:31 
AnswerRe: Atheist & PropertyGrid -> Agnosticism Pin
Marcus Deecke6-Aug-07 21:12
Marcus Deecke6-Aug-07 21:12 
Generalprogramtically Pin
MartyK20071-Aug-07 21:13
MartyK20071-Aug-07 21:13 
AnswerRe: programtically Pin
Robert R Freeman9-Oct-07 6:55
Robert R Freeman9-Oct-07 6:55 
QuestionVery nice - any chance of a C# version? Pin
yojiq30-Jul-07 21:53
yojiq30-Jul-07 21:53 
GeneralSuggestions Pin
Paul Conrad29-Jul-07 7:59
professionalPaul Conrad29-Jul-07 7:59 
GeneralRe: Suggestions Pin
Robert R Freeman30-Jul-07 7:25
Robert R Freeman30-Jul-07 7:25 
GeneralRe: Suggestions Pin
Paul Conrad30-Jul-07 10:54
professionalPaul Conrad30-Jul-07 10:54 
GeneralRe: Suggestions Pin
Robert R Freeman30-Jul-07 11:13
Robert R Freeman30-Jul-07 11:13 
Generalthanks. Pin
Michael Sync24-Jul-07 16:17
Michael Sync24-Jul-07 16:17 
GeneralRe: thanks. Pin
Robert R Freeman25-Jul-07 7:39
Robert R Freeman25-Jul-07 7:39 

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.