Saturday, 1 March 2014

Connect DB Using Class File in C#.NET

Ans:-

Default.aspx:-

<%@ 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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <center>
<asp:gridview ID="Gridview1" runat="server"></asp:gridview>
</center>
    </div>
    </form>
</body>
</html>

Default.aspx.cs:-

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection cn;
    SqlDataAdapter da;
    SqlCommand cmd;
    DataTable dt;
    Class1 obj = new Class1();
    protected void Page_Load(object sender, EventArgs e)
    {
       
        if (!IsPostBack)
        {
            GetDatafrmDb();
        }
    }
    void GetDatafrmDb()
    {
        cn = new SqlConnection(obj.Connection());
        cn.Open();
        if (cn.State == ConnectionState.Open)
        {
            cmd = new SqlCommand();
            cmd.Connection = cn;
            
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "spViewEmpData";
            dt = new DataTable();
            da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            Gridview1.DataSource = dt;
            Gridview1.DataBind();
        }
        cn.Close();

    }
}

For Get Connection through Class file:-
Class1.cs:-

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

/// <summary>
/// Summary description for Class1
/// </summary>
public class Class1
{
    string strcn;
public Class1()
{
        
}
    public string Connection()
    {
        strcn = "server=192.168.0.200;database=subsdb;user id=sa;pwd=amtpl@123";
        return strcn;
    }
}

For Create Table & SP:-

Create table Emp(id int primary key,ename varchar(30),sal money)

create proc spViewEmpData
as
begin
select * from Emp;
end

No comments:

Post a Comment