In this article we discuss about how to bind LINQ to SQL to ObjectDataSource Control and then how to bind ObjectDataSource control to Gridview. Here we bind the SQL table to the Gridview control by using the ObjectDataSource control through DataClassContext object.
public class Departments
{
public Departments()
{
//
// TODO: Add constructor logic here
//
}
public static IEnumerable<Department> GetDepts()
{
DepartmentsDataContext db = new DepartmentsDataContext();
return db.Departments;
}
}
As show above, we are getting Departments data from SQL Server by using LINQ to SQL. In Departments class GetDepts() method returns total departments from Departments SQL Data Table.
Now we have to bind this Departments 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>LINQ to SQL with ObjectDataSource Control</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ObjectDataSource ID="objSrc1" runat="server"
TypeName="Departments" SelectMethod="GetDepts"></asp:ObjectDataSource>
<asp:GridView ID="gv1" runat="server" DataSourceID="objSrc1"></asp:GridView>
</div>
</form>
</body>
</html>
In the above code, we provided the Departments as the TypeName and GetDepts() as method name for ObjectDataSource control. Then provide this ObjectDataSource control id to the Gridview Databound control to display the data.