Binding ObjectDataSource Control to a DataSet

 

By using ObjectDataSource control we can easily bind the databound control such as Gridview, FormView and DetailsView controls with any type of data source.

In this article we discuss about how to bind dataset to ObjectDataSource Control and then how to bind ObjectDataSource control to Gridview. Here we bind the XML file to the Gridview control by using the ObjectDataSource control through DataSet object.

public class Employees : System.Web.UI.Page

{

                public Employees()

                {

                                //

                                // TODO: Add constructor logic here

                                //

                }

 

                public DataSet GetEmployees()

               {

                                DataSet dsEmployees = new DataSet();

                               dsEmployees.ReadXml(Server.MapPath("Employees.xml"));

       

                               return dsEmployees;

               }

}

 

As shown above, we have Employees class has GetEmployees() method which returns the dataset object by reading the XML file Employees.xml.

Now we have to bind this DataSet object to the ObjectDataSource control. ObjectDataSource control expects TypeName and SelectMethod. Generally TypeName is the name of the class and SelectMethod is the name of the method in the class as shown below.

 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Binding the Dataset to the ObjectDataSource Control</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:ObjectDataSource ID="objSource1" runat="server"

        TypeName="Employees"

        SelectMethod="GetEmployees"

        ></asp:ObjectDataSource>

        <asp:GridView ID="gv1" DataSourceID="objSource1" runat="server"></asp:GridView>

    </div>

    </form>

</body>

</html>

 

In the above code, we provided the Employees as the TypeName and GetEmployees() as method name for ObjectDataSource control. Then provide this ObjectDataSource control id to the Gridview Databound control to display the data.

                                                                                                                 ObjectDataSourceDataset.zip (3.86 kb)