ASP.NET: ObjectDataSource – Search 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(int cd)
    {
        cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select * from courses  where cid=@cid";
        cmd.Parameters.AddWithValue("@cid", cd);
        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>
     <center>
     enter course code  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  Please  press enter key!
     
     <br />
     <br />
     <br />
    <asp:GridView ID="GridView2" runat="server"   DataSourceID="ObjectDataSource1" AutoGenerateColumns="false">
    <HeaderStyle  BackColor="Green"  ForeColor="Yellow" />
    <EmptyDataTemplate>
       No Match found
    </EmptyDataTemplate>

    <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">
     <SelectParameters>
         <asp:ControlParameter ControlID="TextBox1"  Name="cd"   Type="Int16" />
        </SelectParameters>
     </asp:ObjectDataSource>
     </center>
    </div>
    </form>
</body>
</html>

4. Output

output

5. 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>