ASP.NET: ObjectDataSource – Show Record

1. SQL Express edition database with sample  rows!

cp2

2. Create a class under App_Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;



using System.Data.SqlClient;
using System.Data;
using System.Configuration;

/// <summary>
/// Summary description for myObject
/// </summary>
public class myObject
{
    SqlConnection cnn;
    SqlCommand cmd;
    SqlDataAdapter ada;
    DataSet ds;
    public myObject()
	{
        cnn = new SqlConnection();
        cnn.ConnectionString = ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString;
	}
    public DataTable getAllRows()
    {
        cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select * from courses";
        cmd.Connection = cnn;
        ada = new SqlDataAdapter();
        ada.SelectCommand = cmd;
        ds = new DataSet();
        ada.Fill(ds);
        DataTable dt = ds.Tables[0];
        return dt;
    }
}

3. Web form

<%@ Page Language="C#"  %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView2" runat="server"   DataSourceID="ObjectDataSource1" AutoGenerateColumns="false">
    <HeaderStyle  BackColor="Green"  ForeColor="Yellow" />
    <Columns>
        <asp:BoundField DataField="cid" HeaderText="Course Code" />
        <asp:BoundField DataField="cname" HeaderText="Name" />
        <asp:BoundField DataField="cduration" HeaderText="Duration" />
        <asp:BoundField DataField="cfees" HeaderText="Fees" />
    
    </Columns>
    </asp:GridView>


     <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"  TypeName="myObject" SelectMethod="getAllRows">
     </asp:ObjectDataSource>
    </div>
    </form>
</body>
</html>

4. output

cp15. web.config (ConnectionString)

<connectionStrings>
    <add name="Myconnection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"
     providerName="System.Data.SqlClient" />
</connectionStrings>