ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Advanced Programming
    CSI-415
    Progress0 / 55 topics
    Topics
    1. Visual Programming Basics2. Introduction to Events3. Fundamentals of Event-Driven Programming4. Message Handling5. User Interfaces6. Graphics Device Interface7. Painting and Drawing8. Windows Management9. Input Devices10. Resources11. String and Menu Resource12. Dialogs and Windows Controls13. Common Controls14. Dynamic Link Libraries (DLLs)15. Threads and Synchronization16. Network Programming17. Building Class Libraries at the Command Line18. Class Libraries19. Using References20. Assemblies21. Private Assembly Deployment22. Shared Assembly Deployment23. Configuration Overview24. Configuration Files25. Programmatic Access to Configuration26. Using SDK Tools for Signing and Deployment27. Metadata28. Reflection29. Late Binding30. Directories and Files31. Serialization32. Attributes33. Memory Management and Garbage Collection34. Threading and Synchronization35. Asynchronous Delegates36. Application Domains37. Marshal by Value38. Marshal by Reference39. Authentication and Authorization40. Configuring Security41. Code Access Security42. Code Groups43. Evidence44. Permissions45. Role-Based Security46. Principals and Identities47. Using Data Readers48. Using Data Sets49. Interacting with XML Data50. Tracing Event Logs51. Using the Boolean Switch and Trace Switch Classes52. Print Debugging Information with the Debug Class53. Instrumenting Release Builds with the Trace Class54. Using Listeners55. Implementing Custom Listeners
    CSI-415›Using Data Sets
    Advanced ProgrammingTopic 48 of 55

    Using Data Sets

    8 minread
    1,308words
    Intermediatelevel

    Using DataSets in ADO.NET

    A DataSet is a central object in ADO.NET for working with data. It is an in-memory representation of data that can be used to hold multiple tables of data, relationships between them, and constraints. Unlike DataReader, which provides a forward-only, read-only way of accessing data, a DataSet provides a more flexible, disconnected model where data can be manipulated and used in various ways.

    A DataSet allows you to work with data from different sources (e.g., SQL Server, Oracle, etc.), without requiring a constant connection to the database. The data can be loaded, edited, and saved back to the database when necessary.

    1. What is a DataSet?

    A DataSet is a collection of DataTable objects, where each DataTable contains rows and columns of data, and you can also define relationships between tables (such as foreign key relationships). Additionally, the DataSet can include constraints (such as primary key constraints) and other metadata for the data it holds.

    A DataSet is disconnected, meaning it does not maintain a live connection to the database once data has been loaded into it. You can edit the data offline and later update the database with the changes.

    2. Key Components of a DataSet

    The key components of a DataSet are:

    • DataTable: Holds the actual data in a tabular form (rows and columns).
    • DataColumn: Defines the schema for the DataTable, specifying the type of data each column holds.
    • DataRow: Represents a single row in a DataTable.
    • DataRelation: Defines the relationships between different DataTable objects (similar to foreign keys).
    • Constraints: Defines rules like primary keys and uniqueness constraints for the tables.

    3. Creating and Populating a DataSet

    You can create a DataSet and populate it in several ways, such as by using DataAdapter to fill it with data from a database. The DataAdapter acts as a bridge between the database and the DataSet. It retrieves data from the database and populates the DataSet, and can also be used to update the database.

    Example: Creating a DataSet and Filling It

    The following example demonstrates how to create a DataSet, populate it using a DataAdapter, and display the data in a DataTable.

    using System;
    using System.Data;
    using System.Data.SqlClient;
    
    public class DataSetExample
    {
        public void LoadDataSet()
        {
            string connectionString = "Data Source=YourServerName;Initial Catalog=YourDatabase;Integrated Security=True";
            string query = "SELECT EmployeeID, FirstName, LastName, Age FROM Employees";
    
            // Create a DataSet object
            DataSet dataSet = new DataSet();
    
            // Create a SqlConnection and SqlDataAdapter
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
    
                // Fill the DataSet with data from the database
                adapter.Fill(dataSet, "Employees");
    
                // Now, the DataSet contains the data in the "Employees" table
            }
    
            // Access the DataTable from the DataSet
            DataTable employeeTable = dataSet.Tables["Employees"];
    
            // Display the data from the DataTable
            foreach (DataRow row in employeeTable.Rows)
            {
                Console.WriteLine($"ID: {row["EmployeeID"]}, Name: {row["FirstName"]} {row["LastName"]}, Age: {row["Age"]}");
            }
        }
    }
    

    Explanation of the Example:

    • DataSet Creation: A DataSet object is created, and a DataAdapter is used to fetch data from the database.
    • SqlDataAdapter: The SqlDataAdapter.Fill() method fills the DataSet with data from the database using the SQL query.
    • Accessing the DataTable: The data is stored in the DataSet under the name "Employees". You can access this DataTable and read the data from it.

    4. Working with DataTables in a DataSet

    A DataSet can contain multiple DataTable objects, allowing you to work with more than one table of data at once. You can access these tables by their name or index.

    Example: Working with Multiple DataTables

    DataSet dataSet = new DataSet();
    
    // Add DataTables to the DataSet
    DataTable employeesTable = new DataTable("Employees");
    DataTable departmentsTable = new DataTable("Departments");
    
    dataSet.Tables.Add(employeesTable);
    dataSet.Tables.Add(departmentsTable);
    
    // Fill the DataTables with data (using SqlDataAdapter or manually)
    

    You can use the Tables collection of the DataSet to manage and access multiple tables:

    DataTable employees = dataSet.Tables["Employees"];
    DataTable departments = dataSet.Tables["Departments"];
    

    5. Data Relations Between Tables

    A DataSet can also contain relationships between different DataTable objects. These relationships allow you to represent the foreign key relationships between tables (such as between an Employees table and a Departments table).

    Example: Creating a DataRelation

    DataSet dataSet = new DataSet();
    
    // Create the DataTables
    DataTable employees = new DataTable("Employees");
    DataTable departments = new DataTable("Departments");
    
    // Add columns to the Employees table
    employees.Columns.Add("EmployeeID", typeof(int));
    employees.Columns.Add("FirstName", typeof(string));
    employees.Columns.Add("DepartmentID", typeof(int));
    
    // Add columns to the Departments table
    departments.Columns.Add("DepartmentID", typeof(int));
    departments.Columns.Add("DepartmentName", typeof(string));
    
    // Add the tables to the DataSet
    dataSet.Tables.Add(employees);
    dataSet.Tables.Add(departments);
    
    // Define a relationship between the tables
    DataRelation relation = new DataRelation(
        "EmployeeDepartmentRelation", 
        departments.Columns["DepartmentID"], 
        employees.Columns["DepartmentID"]);
    
    dataSet.Relations.Add(relation);
    

    In this example, the DataRelation object is used to define the relationship between the Employees table and the Departments table, linking the DepartmentID column in both tables.


    6. Manipulating Data in a DataSet

    Once the data is in a DataSet, you can perform various operations on it, such as:

    • Adding rows: You can use the NewRow() method of the DataTable to create a new row and then add it to the table using Rows.Add().

    • Modifying data: You can directly modify the values in a DataRow object.

    • Deleting rows: You can mark rows for deletion using the Delete() method of the DataRow object.

    Example: Adding, Modifying, and Deleting Rows

    // Adding a new row
    DataRow newRow = employees.NewRow();
    newRow["EmployeeID"] = 101;
    newRow["FirstName"] = "John";
    newRow["DepartmentID"] = 1;
    employees.Rows.Add(newRow);
    
    // Modifying an existing row
    DataRow existingRow = employees.Rows[0];
    existingRow["FirstName"] = "Jane";
    
    // Deleting a row
    DataRow rowToDelete = employees.Rows[1];
    rowToDelete.Delete();
    

    7. Updating the Database Using DataSet

    After modifying the DataSet, you can use a DataAdapter to update the database. The Update() method of the DataAdapter is used to push changes back to the database. The DataAdapter will automatically generate the appropriate INSERT, UPDATE, or DELETE commands based on the changes made to the DataSet.

    Example: Updating the Database

    using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Employees", connectionString))
    {
        SqlCommandBuilder builder = new SqlCommandBuilder(adapter); // Generates commands for Insert, Update, Delete
        
        // Apply changes made to the DataSet
        adapter.Update(dataSet, "Employees");
    }
    

    This code uses SqlCommandBuilder to automatically generate the necessary SQL commands for updating, inserting, or deleting records in the database based on the changes made in the DataSet.


    8. Advantages of Using DataSet

    • Disconnected Model: The DataSet allows you to work with data without maintaining an open connection to the database. This is useful for scenarios where you want to perform offline data manipulation.
    • Multiple Tables: It can hold multiple tables, making it ideal for applications that need to work with related sets of data.
    • Data Manipulation: You can modify data locally, and later update the database with changes.
    • Relationships: You can define relationships between different tables in a DataSet, allowing you to work with complex data models.

    Conclusion

    A DataSet is a powerful object in ADO.NET that allows you to work with data in a disconnected way, providing flexibility to manipulate and update data offline. It can hold multiple tables, define relationships between them, and supports operations like adding, modifying, and deleting rows. When combined with a DataAdapter, you can easily interact with the database, making it a key component for applications requiring robust data management.

    • When to Use: Use DataSet when you need to work with multiple tables, need to manipulate data offline, or require relational data.
    • Key Features:
    Previous topic 47
    Using Data Readers
    Next topic 49
    Interacting with XML Data

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time8 min
      Word count1,308
      Code examples0
      DifficultyIntermediate