FunctionX Practical Learning Logo

Data Entry With a Data Grid (SQL)

 

Introduction

If you have used tables in SQL Server, Microsoft Access, Paradox, and other database environments, you probably know that their tables automatically save data as the user changes records and moves through cells. Although it is one of the most regularly used objects of databases in Microsoft Visual .NET, the DataGrid control doesn't inherently provide this functionality, but for a good reason. By default, the DataGrid control is not meant for databases only. When a DataGrid control displays data, it allows a user to enter new data but doesn't save it.

Data entered in a DataGrid is extremely easy to save. This is simply taken care of by calling the Update method of your data adapter.

 

Practical LearningPractical Learning: Performing Data Entry

  1. Open SQL Data Analyzer
  2. If you haven't yet (only if you haven't), create the AlleyTechno database
  3. If you haven't yet (only if you haven't), create the Departments table
  4. If you haven't yet (only if you haven't), create the Employees table
  5. Open Visual C++ .NET and create a new Windows Forms Application named DataEntry1
  6. From Server Explorer, open the server that holds the above database then expand the AlleyTechno database followed by the Tables node
  7. Drag the Employees table and drop it on the form
  8. Right-click the newly added sqlDataAdapter1 and click Generate Dataset...
  9. While the New radio button is selected, change the name of the dataset to dsEmployees
     
    Generate Dataset
  10. Click OK
  11. From the Toolbox, click DataGrid and click the form
  12. Move the DataGrid control to the upper-left section of the form and set its Anchor property to Top, Bottom, Left, Right
  13. Right-click the DataGrid and click Auto Format
  14. In the Auto Format dialog box, select Colorful 2
     
    Auto Format
  15. Click OK
  16. Set the DataGrid control's Data Source to dsEmployees1.Employees
     
  17. Double-click an empty area of the form and change the Load event as follows:
     
    private void btnLoad_Click(object sender, System.EventArgs e)
    {
    	 this.sqlDataAdapter1.Fill(this.dsEmployees1);
    }
  18. Press Ctrl + F5 to test the application
  19. Enter a new record and navigate to a different record. Close the form and execute the application again. Notice that the record you added was not saved
  20. To allow the user to create a new record and/or to update new changes, on the form, click the DataGrid control
  21. In the Properties window, click the Events button Events
  22. Double-click the CurrentCellChanged event and implement it as follows:
     
    private void dataGrid1_CurrentCellChanged(object sender, System.EventArgs e)
    {
    	 this.sqlDataAdapter1.Update(this.dsEmployees1);
    }
  23. Press Ctrl + F5 to test the application
  24. Create a new record by entering new information
 
 

Home Copyright © 2004-2011 FunctionX