asp.net ObjectDataSource example: populate GridView
GridViewObjectDataSourceExample.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net ObjectDataSource example: populate GridView</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Navy">GridView ObjectDataSource Example</h2>
<asp:ObjectDataSource
ID="ObjectDataSource1"
runat="server"
TypeName="EmployeeList"
SelectMethod="GetEmployees"
>
</asp:ObjectDataSource>
<asp:GridView
ID="GridView1"
runat="server"
DataSourceID="ObjectDataSource1"
DataKeyNames="EmployeeID"
AllowPaging="true"
BackColor="LightPink"
ForeColor="Crimson"
BorderColor="Pink"
AutoGenerateColumns="false"
HeaderStyle-BackColor="Crimson"
HeaderStyle-ForeColor="LightPink"
PageSize="5"
>
<Columns>
<asp:BoundField HeaderText="EmployeeID" DataField="EmployeeID" />
<asp:BoundField HeaderText="Last Name" DataField="LastName" />
<asp:BoundField HeaderText="First Name" DataField="FirstName" />
<asp:BoundField HeaderText="Title" DataField="Title" />
<asp:BoundField HeaderText="City" DataField="City" />
<asp:BoundField HeaderText="Country" DataField="Country" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
EmployeeList.cs
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public class EmployeeList
{
public EmployeeList(){}
public DataSet GetEmployees()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
SqlCommand myCommand = new SqlCommand();
myCommand.CommandText = "SELECT EmployeeID, LastName, FirstName, Title, City, Country FROM Employees";
myCommand.Connection = conn;
SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
DataSet myDataSet = new DataSet();
myAdapter.Fill(myDataSet);
return myDataSet;
}
}