Saturday, 1 March 2014

Connect DB Using Class File in VB.NET

Ans:-

Default.aspx:-

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" 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:-

Imports System
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
    Inherits System.Web.UI.Page
    Dim cl As New Class1
    Dim scn As SqlConnection
    Dim cmd As SqlCommand
    Dim dt As DataTable
    Dim da As SqlDataAdapter

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Page.IsPostBack <> True Then
            BindData()
        End If

    End Sub
    Sub BindData()
        scn = New SqlConnection(cl.Connect())
        scn.Open()
        cmd = New SqlCommand()
        cmd.Connection = scn
        cmd.CommandType = CommandType.StoredProcedure
        cmd.CommandText = "spViewEmpData"
        da = New SqlDataAdapter(cmd)
        dt = New DataTable()
        da.Fill(dt)
        scn.Close()
        GridView1.DataSource = dt
        GridView1.DataBind()

    End Sub
End Class

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

Imports Microsoft.VisualBasic

Public Class Class1
    Public Function Connect() As String

        Dim strCon As String = "server=.;database=subsdb;user id=sa;pwd=123"
        Return strCon
    End Function
End Class

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