In this article we will introduce with ObjectDataSource control in ASP.NET using C#.
ObjectDataSource Example in ASP.NET using C#
In this article we will discuss how to use a ObjectDataSource in your application. ObjectDataSource similar like other data sources as SqlDataSources, EntityDataSources, XmlDataSources etc. Firstly we will make a class and methods for bind, delete, update and select a record.
ProductList.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; using System.Web.Configuration; public class ProductList { public ProductList() { } SqlConnection con; SqlCommand cmd; SqlDataAdapter da; DataSet ds; public DataSet GetProducts() { con = new SqlConnection(); con.ConnectionString = WebConfigurationManager.ConnectionStrings["ChartDatabaseConnectionString"].ConnectionString; cmd = new SqlCommand(); cmd.CommandText = "Select ProductID, ProductName, Price from Product"; cmd.Connection = con; da = new SqlDataAdapter(cmd); ds = new DataSet(); da.Fill(ds); return ds; } }
In this example we use a DataGrid and provide data using ObjectDataSource. Now Click on smart tag button of GridView and Choose data Source. Now select ObjectDataSource and click OK.
Now Choose Business Object and click next.
Now Define Data Methods and click finish.
ObjectDataSource.aspx (Design Page):
ObjectDataSource.aspx (source code):
<%@ Page Title="" Language="C#" MasterPageFile="~/RoseindiaMaster.master" AutoEventWireup="true" CodeFile="ObjectDataSource.aspx.cs" Inherits="ObjectDataSource" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <div> <h2 style="color:Green">ObjectDataSource in ASP.NET 4, C#</h2> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" CellPadding="4" DataSourceID="ObjectDataSource1" ForeColor="#333333" GridLines="None" PageSize="4"> <AlternatingRowStyle BackColor="White" /> <Columns> <asp:CommandField ShowSelectButton="True" /> </Columns> <EditRowStyle BackColor="#2461BF" /> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#EFF3FB" /> <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> <SortedAscendingCellStyle BackColor="#F5F7FB" /> <SortedAscendingHeaderStyle BackColor="#6D95E1" /> <SortedDescendingCellStyle BackColor="#E9EBEF" /> <SortedDescendingHeaderStyle BackColor="#4870BE" /> </asp:GridView> <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetProducts" TypeName="ProductList"></asp:ObjectDataSource> </div> </asp:Content>
[ 0 ] Comments