Serial Number 1 2

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 61
At a glance
Powered by AI
The document discusses various aims and programs related to servlets, JSP, .NET and database connectivity.

The document discusses two ways to run servlet programs - without IDE and using an IDE like Netbeans.

The document outlines the steps to create a servlet program in Netbeans like creating a new project, package, servlet file etc.

Index

Serial Date Particulars Page Signature


Number Number
1 Aim : How to run and compile 3
Servlet programs
2 Aim: Write a servlet program to 4
display Hello Word
3 Aim: Write a Servlet Program to 5
display current date and time
4 Aim: Write a servlet program to 6
keep track of how many times
the servlet has been accessed
5 Aim: Write a servlet program to 7
display the Protocol, URL and
Remote Address
6 Aim: Write servlet program to 8
display the user form with
authentication

7 Aim: Introduction to Java Server 15


Pages(JSP)
8 Aim: Write a JSP program to 18
display the date
9 Aim: Write a program in servlet 19
to display method used, URL,
protocol, Server Name, Server
Port, Remote Address, Remote
Host
10 Aim: write a jsp program to 21
display the data entered by the
user in the form
11 Aim: Write a jsp program to 23
demonstrate the use of
Decraltives
12 Aim: Write a program to 25
demonstrate the use of import
attribute of directive tag.
13 Aim: Write a jsp program to 27
demonstrate the use of buffer
and autoflush attribute
14 Aim: Write a program to 28
demonstrate the use of Include
directive:

1
.Net Programming
15 Aim: WAP to show functionality 29
of Calculator
16 WAP to show the swap 32
functionality of integer, string &
float value using generics.
17 WAP to illustrate the concept of 33
generics.
18 WAP to calculate the Area of 34
Rectangle & Area of Square using
Method Overloading
19 File Handling Examples 36
a. Create a New File 36
b. Write in a File 37
c. Read from the File 38
20 WAP for Shopping Cart 39
21 Database Connectivity For 56
Student Information

2
Aim : How to run and compile Servlet programs
There are two methods to run the servlet program:
Without IDE
Using IDE

Without IDE
write a servlet program in notepad and save it to (C:\Program Files\Apache Software
Foundation\Tomcat 6.0\webapps\examples\WEB-INF\classes)
Create .class file of your servlet class by compiling it in command prompt.
web.xml to include servlet’s name and url pattern. (Web xml file which is present in WEB-INF folder).
Click on Apache tomcat server to start the service.
run your servlet file using url which u have defined in we.xml at apache server as:
http://localhost/demo-examples/HelloServlet
url=demo-exmaple
servlet name=HelloServlet

Using IDE
Start netbeans 5.0
Go to file menu and create new project (e.g.: ServletsProgram).
you can create your own package as:
Right click on source package.
Select java package and name the package (e.g. ABC).
Now right click on ABC and select new Servlet file.
You can also create new servlet file in default package by selecting the new servlet file option from
WEBINF.

3
Servlet Programs:
Practical No.1
Write a servlet program to display Hello Word.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet

   public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException,IOException
{
     response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
     pw.println("<html>");
    pw.println("<head><title>Hello World</title></title>");
    pw.println("<body>");
     pw.println("<h1>Hello World</h1>");
     pw.println("</body></html>");
   }
}
Output:

4
Write a Servlet Program to display current date and time.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TimeUpdater extends HttpServlet


{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter pw = response.getWriter();
response.addHeader("Refresh", "1");
pw.println(new Date().toString());
}
}
Output:

5
Write a servlet program to keep track of how many times the servlet has been accessed
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SimpleCounter extends HttpServlet
{
  int counter = 0;
   public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException
 {
     response.setContentType("text/html");
     PrintWriter pw = response.getWriter();
     counter++;
     pw.println("At present the value of the counter is " + counter);
   }
}
Output:

6
Practical No.2
Write a servlet program to display the Protocol, URL and Remote Address.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RequestInfo extends HttpServlet


{

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("<title>Request Information Example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h3>Request Information Example</h3>");
out.println("Method: " + request.getMethod());
out.println("Request URI: " + request.getRequestURI());
out.println("Protocol: " + request.getProtocol());
out.println("PathInfo: " + request.getPathInfo());
out.println("Remote Address: " + request.getRemoteAddr());
out.println("</body>");
out.println("</html>");
}

/**
* We are going to perform the same operations for POST requests
* as for GET methods, so this method just sends the request to
* the doGet method.
*/

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws IOException, ServletException
{
doGet(request, response);
}
}

7
Write servlet program to display the user form with authentication
//NewServlet.java
public class NewServlet extends HttpServlet {

/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Application Form</title>");
out.println("</head>");
out.println("<form action=NewServlet1 method=get>");

out.println("<body>");
out.println("<h1>Application Form </h1> " + "<h4><br>WELCOME </h4><br><font name=Lucida
Sans Typewriter> Enter Your Name </font>" + "<br><input Type=text name=UserName size=20>" );
out.print("Password <input Type=text name = password>");

out.print("<br><input Type=checkbox name=cb1 value=reading><font name=Lucida Sans


Typewriter>Reading </font> ");

out.print("<br><input Type=checkbox name = cb1 value=writing><font name=Lucida Sans


Typewriter> Writing </font> ");

out.print("<br><input Type=checkbox name=cb1 value=shopping><font name=Lucida Sans


Typewriter>Shopping </font> ");
// out.println("<br> This space is courtesy Sasdgasgd <br>");
//for (int i=1;i<=10;i++)
// {

// out.println("5 * " + i + " = " + 5*i );


// out.println("<br>");

// }
out.println("<br><input type=Submit value=Submit>");
out.println("");
out.println("</body>");
out.println("</html>");

/* TODO output your page here


out.println("<html>");

8
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet NewServlet at " + request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
*/
out.close();
}

//NewServlet1.java

public class NewServlet1 extends HttpServlet {

/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String s1 = request.getParameter("UserName" );
String s3 = request.getParameter("password" );
if (s1.equals("hiray") && s3.equals("college"))
{
out.println("You have choosen: ");
out.println(s1 + "<br>");
out.println(s3 + "<br>");

String s2[]=request.getParameterValues("cb1");
for (int i=0; i<s2.length;i++)
{
out.println( s2[i] + "<br>" );

}
}
else

out.println("Error");

9
/* TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet1</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet NewServlet1 at " + request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
*/
out.close();
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to


edit the code.">
/** Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Handles the HTTP <code>POST</code> method.


* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/** Returns a short description of the servlet.


*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}

10
11
12
13
Java Server Pages(JSP):

14
JSP TAGS
In this lesson we will learn about the various tags available in JSP with suitable examples. In JSP tags can
be divided into 4 different types. These are:
    
Directives
In the directives we can import packages, define error handling pages or the session information of the
JSP page.
    
Declarations
This tag is used for defining the functions and variables to be used in the JSP.
   
Scriplets
In this tag we can insert any amount of valid java code and these codes are placed in _jspService method
by the JSP engine.
   
Expressions
We can use this tag to output any data on the generated page. These data are automatically converted
to string and printed on the output stream.
   
Syntax of JSP directives is:
<%@directive attribute="value" %>
Where directive may be:
page: page is used to provide the information about it.
Example: <%@page language="java" %> 
   
include: include is used to include a file in the JSP page.
Example: <%@ include file="/header.jsp" %> 
  
taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own
tags).
Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %> 
   

and attribute may be:


language="java"
This tells the server that the page is using the java language. Current JSP specification supports only java
language.
Example: <%@page language="java" %> 
   
extends="mypackage.myclass"
This attribute is used when we want to extend any class. We can use comma(,) to import more than one
packages.
Example: <%@page language="java" import="java.sql.*,mypackage.myclass"%> 
   

15
session="true"
When this value is true session data is available to the JSP page otherwise not. By default this value is
true.
Example: <%@page language="java" session="true" %> 
  
errorPage="error.jsp"
errorPage is used to handle the un-handled exceptions in the page.
Example: <%@page language="java" session="true" errorPage="error.jsp"  %> 
   
contentType="text/html;charset=ISO-8859-1"
Use this attribute to set the mime type and character set of the JSP.
Example: <%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1"  %> 

Syntax of JSP Declaratives are:


  <%!
  //java codes
   %>
JSP Declaratives begins with <%! and ends %> with .We can embed any amount of java code in the JSP
Declaratives. Variables and functions defined in the declaratives are class level and can be used
anywhere in the JSP page.

Syntax of JSP Scriptles are:


  <%
  //java codes
   %>
JSP Scriptlets begins with <% and ends %> .We can embed any amount of java code in the JSP Scriptlets.
JSP Engine places these code in the _jspService() method. Variables available to the JSP Scriptlets are:
request:
request represents the clients request and is a subclass of HttpServletRequest. Use this variable to
retrieve the data submitted along the request.
Example:
  <%
  //java codes
   String userName=null;
   userName=request.getParameter("userName");
   %>
response:
response is subclass of HttpServletResponse.
 
session:
session represents the HTTP session object associated with the request. 
out:
out is an object of output stream and is used to send any output to the client.
Syntax of JSP Expressions are:
  <%="Any thing"   %>
JSP Expressions start with 

16
Syntax of JSP Scriptles are with <%= and ends with  %>. Between these this you can put anything and
that will converted to the String and that will be displayed.
Example:
  <%="Hello World!" %>
Above code will display 'Hello World!'.

17
Practical No.3
Write a JSP program to display the date.

<html>
<body bgcolor=”pink”>
<%= new java.util.Date() %>
</body>
</html>

Output:

18
Write a program in servlet to display method used, URL, protocol, Server Name, Server Port, Remote
Address, Remote Host.
html>
<body>
<p><b><h1><font size="5" color="#800000">Request Information:</font><h1></b></p>
<div align="left">
<table border="1" cellpadding="0" cellspacing="0" width="70%" bgcolor="lightblue">
<tr>
<td width="33%"><h2><b><font color="#800000">Request Method:</font></b></h2></td>
<td width="67%"><font color="#FF0000"><h2><%=request.getMethod()%></font></h2></td>
</tr>
<tr>
<td width="33%"><h2><b><font color="#800000">Request URI:</font></b><h2></td>
<td width="67%"><h2><font color="#FF0000"><%=request.getRequestURI()%></font><h2></td>
</tr>
<tr>
<td width="33%"><h2><b><font color="#800000">Request Protocol:</font></b><h2></td>
<td width="67%"><h2><font color="#FF0000"><%=request.getProtocol()%></font><h2></td>
</tr>
<tr>
<td width="33%"><h2><b><font color="#800000">Server name:</font></b><h2></td>
<td width="67%"><h2><font color="#FF0000"><%=request.getServerName()%></font><h2></td>
</tr>
<tr>
<td width="33%"><h2><b><font color="#800000">Server port:</font></b><h2></td>
<td width="67%"><h2><font color="#FF0000"><%=request.getServerPort()%></font><h2></td>
</tr>
<td width="33%"><h2><b><font color="#800000">Remote address:</font></b><h2></td>
<td width="67%"><h2><font color="#FF0000"><%=request.getRemoteAddr()%></font><h2></td>
</tr>
<tr>
<td width="33%"><h2><b><font color="#800000">Remote host:</font></b><h2></td>
<td width="67%"><h2><font color="#FF0000"><%=request.getRemoteHost()%></font><h2></td>
</tr>
</table>
</div>
</body>
</html>

19
20
Practical No.4

write a jsp program to display the data entered by the user in the form.

inform.jsp
<html>
<head>
<title>User's Information</title>
</head>
<body>
<p>&nbsp;</p>
<form method="POST" action="showname.jsp">

<p><font color="#800000" size="5">Enter your name:</font><input type="text" name="username"


size="20"></p>

<p><font color="#800000" size="5">Enter your city:</font><input type="text" name="city"


size="20"></p>

<p><input type="submit" value="Submit" name="B1"></p>


</form>
</body>
</html>

showname.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<p><font size="6">Welcome :&nbsp; <%=request.getParameter("username")%></font></p>

<p><font size="6">Your city name is :&nbsp; <%=request.getParameter("city")%></font></p>


</body>
</html>

21
output:

22
Write a jsp program to demonstrate the use of Decraltives.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%!
int cnt=0;
private int getCount()
{
cnt++;
return cnt;
}
%>
<p>Values of Cnt are:</p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
//increment cnt and return the value
</body>
</html>

23
output:

24
Write a program to demonstrate the use of import attribute of directive tag.

JSP file:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<%@page import="newpackage.NewClass, newpackage.Solution" %>


<title>Import attribute of page Directive in JSP</title>
</head>

<body>
<font size="10" color="red">
<%
Solution ex = new Solution();
out.print(ex.show());
%>
<br>
<%
NewClass nw = new NewClass();
out.print(nw.show11());
%>
</font>
</body>
</html>

NewClass.java

package newpackage;

public class NewClass


{
/** Creates a new instance of NewClass */
public String show11()
{
return "this form NewClass";
}
}

Solution.java

package newpackage;

public class Solution

25
{
/** Creates a new instance of Solution */
public String show()
{
return "this is from soultion class";
}
}
output:

26
Write a jsp program to demonstrate the use of buffer and autoflush attribute.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%@page buffer="none" autoFlush="true" %>
<%
for(int i = 0; i < 20; i++)
{
out.println("<html><body><img src=ok.jpg height=300 width=200/></body></html>");
}
%>
</body>
</html>

Output :

27
Write a program to demonstrate the use of Include directive:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>includeing different files using Include tag</title>
<%@ include file="one.jsp" %>
<%@ include file="two.jsp" %>
<%@ include file="three.html" %>

</head>
</html>

Output :

28
.Net Programming

Program 1: WAP to show functionality of Calculator.

Source Code:

CalculatorMain.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Calculator
{
class calculatormain
{
static void Main(string[] args)
{
string p;
do
{
Console.Write("Enter 1st no. ");
int a=Convert.ToInt32(Console.ReadLine());
Console.Write("Enter 2nd no. ");
int b=Convert.ToInt32(Console.ReadLine());
calculatormethod abc = new calculatormethod(a, b);
Console.WriteLine("Press any option");
Console.WriteLine("Press 1 to Add");
Console.WriteLine("Press 2 to Subtract");
Console.WriteLine("Press 3 to Multiply");
Console.WriteLine("Press 4 to Divide");
Console.WriteLine("Press 5 to Exit");
Console.Write("Enter your choice: ");
string c=Console.ReadLine();

switch (c)
{
case "1":
abc.add();
break;
case "2":
abc.minus();
break;

29
case "3":
abc.multiply();
break;
case "4":
abc.divide();
break;
default:
Environment.Exit(0);
break;
}
Console.Write("Do you want to continue (y/n) ");
p=Console.ReadLine();
}while(p=="y");
}
}
}

CalculatorMethod.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Calculator
{
class calculatormethod
{
int n, m, res;
public calculatormethod(int a, int b)
{
n = a;
m = b;
}
public void add()
{
res = n + m;
Console.WriteLine("Addition = " + res);
}

public void minus()


{
res = n - m;
Console.WriteLine("Subtraction = " +res);
}
public void multiply()
{

30
res = n * m;
Console.WriteLine("Multiplication = " +res);
}
public void divide()
{
res = n / m;
Console.WriteLine("Division = " + res);
}
}
}
Output:

Enter 1st no. 7


Enter 2nd no. 12

Press any option


Press 1 to Add
Press 2 to Subtract
Press 3 to Multiply
Press 4 to Divide
Press 5 to Exit

Enter your choice: 3


Multiplication = 84
Do you want to continue (y/n) n

31
Program 2: WAP to show the swap functionality of integer, string &
float value using generics.

Source Code:

SwapExample.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericsExample
{
class SwapExample
{
static void Main(string[] args)
{
int a = 12;
int b = 7;
Console.WriteLine("Values Before Swap:");
Console.WriteLine("a = " + a + "\tb= " + b);
GenericProgram objgp = new GenericProgram();
objgp.swap<int>(ref a, ref b);
Console.WriteLine("Values After Swap:");
Console.WriteLine("a = " + a + "\tb= " + b);
string str1 = "hello";
string str2 = "world";
Console.WriteLine("Values Before Swap:");
Console.WriteLine("str1 = " + str1 + "\tstr2= " + str2);
objgp.swap<string>(ref str1, ref str2);
Console.WriteLine("Values After Swap:");
Console.WriteLine("str1 = " + str1 + "\tstr2= " + str2);
float f1 = 12.07f;
float f2 = 7.12f;
Console.WriteLine("Values Before Swap:");
Console.WriteLine("f1 = " + f1 + "\tf2= " + f2);
objgp.swap<float>(ref f1, ref f2);
Console.WriteLine("Values After Swap:");
Console.WriteLine("f1 = " + f1 + "\tf2= " + f2);
}
}
}

32
GenericsExample.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericsExample
{
public class GenericProgram
{
public void swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
}
}

Output:

Values Before Swap:


a = 12 b= 7

Values After Swap:


a = 7 b= 12

Values Before Swap:


str1 = hello str2= world

Values After Swap:


str1 = world str2= hello

Values Before Swap:


f1 = 12.07 f2= 7.12

Values After Swap:


f1 = 7.12 f2= 12.07

33
Program 3: WAP to calculate the Area of Rectangle & Area of Square
using Method Overloading.

Source Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Overloading
{
class Overload
{
static void Main(string[] args)
{
int l, b;
string ch;
Overload obj=new Overload();
do
{
Console.WriteLine("Select one option");
Console.WriteLine("1. Area of Rectangle");
Console.WriteLine("2. Area of Square");
Console.WriteLine("3. Exit");
Console.Write("Select any option: ");
string c = Console.ReadLine();
switch (c)
{
case "1":
{
Console.Write("Enter Length: ");
l = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Width: ");
b = Convert.ToInt32(Console.ReadLine());
obj.area(l, b);
break;
}
case "2":
{
Console.Write("Enter Side: ");
l = Convert.ToInt32(Console.ReadLine());
obj.area(l);
break;
}
default:

34
Environment.Exit(0);
break;
}
Console.Write("Do You want to continue (y/n): ");
ch = Console.ReadLine();
}while(ch == "y");
}
void area(int l, int b)
{
int res = l * b;
Console.WriteLine("Area of Rectangle= " + res);
}
void area(int a)
{
int res = a * a;
Console.WriteLine("Area of Square= " + res);
}
}
}

Output:

Select one option


1. Area of Rectangle
2. Area of Square
3. Exit
Select any option: 1

Enter Length: 7
Enter Width: 12

Area of Rectangle= 84

Do You want to continue (y/n): y

Select one option


1. Area of Rectangle
2. Area of Square
3. Exit
Select any option: 2

Enter Side: 12

Area of Square= 144

Do You want to continue (y/n): n

35
Program 4: File Handling Examples

a. Create a New File

Source Code:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FileHandlingExample
{
class Program
{
public static void Main(string[] args)
{
try
{
string path1="C:/temp/myfile.doc";
StreamWriter sw=null;
if(!File.Exists(path1))
{
sw=File.CreateText(path1);
Console.WriteLine("File Created");
}
else
{
Console.WriteLine("File Exits");
}
sw.WriteLine("Welcome to MCA TY");
sw.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}

Output:

File Created

36
b. Write in a File

Source Code:

using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FileHandlingExample
{
class WriteFile
{
public static void Main()
{

FileStream fs=null;
string path1 = "C:/temp/myfile.doc";
try
{
if(File.Exists(path1))
{
fs = File.Open(path1, FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
Console.WriteLine("Enter your Data that you to
Write in to File");
sw.WriteLine(Console.ReadLine());
sw.WriteLine("Data written in file");
sw.Close();
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}

Output:

Data written in file

37
c. Read from the File

Source Code:

using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FileHandlingExample
{
class ReadAppend
{
public static void Main()
{
FileStream fin=null;
string path1 = "C:/temp/myfile.doc";
string s;
try
{
fin = new FileStream(path1, FileMode.Open);
}
catch (FileNotFoundException e)
{
Console.WriteLine(e.Message);
}
StreamReader sr = new StreamReader(fin);
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
sr.Close();
Console.ReadLine();
}
}
}

Output:

Welcome to MCA TY
Hello!!! Welcome to YMT College.
Data written in file
Good morning
All Friends

38
5. WAP for Shopping Cart

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Menu.master.cs"


Inherits="ShoppingChart.Menu" %>

<!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 id="Head1" runat="server">


<title>Untitled Page</title>
<link href="../App_Themes/CSSExample1.css" rel="stylesheet" type="text/css" />

<asp:ContentPlaceHolder ID="head" runat="server">

</asp:ContentPlaceHolder>

</head>
<body>
<form id="form1" runat="server">

<asp:Menu ID="Menu1" runat="server" Height="21px" Orientation="Horizontal"


Width="734px" >
<StaticMenuStyle />
<DynamicMenuStyle />
<DynamicHoverStyle />
<DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
<Items>
<asp:MenuItem Text="Masters" Value="Masters">
<asp:MenuItem Text="CustomerMaster" Value="CustomerMaster"
Target="CustomerMaster.aspx"></asp:MenuItem>
<asp:MenuItem Target="PlaceOrder.aspx" Text="PlaceOrder" Value="PlaceOrder">
</asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Reports" Value="Reports"></asp:MenuItem>
</Items>
</asp:Menu>
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

</asp:ContentPlaceHolder>
</div>
</form>
</body>

39
</html>
Web.config File (Connection Strings)

<connectionStrings>

<add name="con"

connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\shrenik\sem
5\awt\journal\awt_prct\awt_prct\ShoppingChart\ShoppingChart\ShoppingChart\App_Data\Database1.
mdf;Integrated Security=True;User Instance=True"

providerName="System.Data.SqlClient" />

</connectionStrings>

40
Shop.aspx

<%@ Page Language="C#" MasterPageFile="~/Menu.Master" AutoEventWireup="true"


CodeBehind="Shop.aspx.cs" Inherits="ShoppingChart.Shop" %>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">


<br />
<br />
<asp:HiddenField ID="hidCustomerId" runat ="server"
/>
<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td valign="top" width="74%">
<table width="75%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td class="TextHead">
Customer Master- Create New
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
</tr>
<tr>
<td>
<table cellspacing="0" cellpadding="0" width="623" border="0">
<tbody>
<tr>
<td colspan="3" style="height: 10px">
&nbsp;&nbsp;
<asp:Label ID="lblmsg" name="lblmsg" CssClass="Normal" ForeColor="Red"
runat="server"
Width="326px"></asp:Label>
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp;
&nbsp; &nbsp;&nbsp;
</td>
</tr>
<tr>

41
<td width="15">
</td>
<td>
<!--//Personal Details Section starts Here//-->
<table cellspacing="0" cellpadding="0" width="600" border="0">
<tbody>
<tr>
<td colspan="4" style="height: 5px">
</td>
</tr>

<tr>
<td colspan="4" height="5">
</td>
</tr>

<tr>
<td colspan="4" height="5">
</td>
</tr>
<tr>
<td class="fieldText" width="173" style="height: 20px">
Name of the Customer
</td>
<td class="fieldText" width="4" style="height: 20px">
<b>:</b>
</td>
<td width="22" style="height: 20px">
</td>
<td valign="top" class="style3">
<asp:TextBox runat="server" name="txtCustomerName"
ID="txtCustomerName" class="ActiveTextBox"
MaxLength="20" ToolTip="Max limit 20"></asp:TextBox>
</td>
</tr>
<tr>
<td style="height: 5px" colspan="4">
</td>
</tr>

<tr>
<td style="height: 5px" colspan="4">
</td>
</tr>

<tr>
<td colspan="4" height="5">
</td>

42
</tr>

<tr>
<td colspan="4" height="5">
</td>
</tr>

<tr>
<td class="fieldText" width="173" style="height: 25px">
Select Products
</td>
<td class="fieldText" width="4" style="height: 25px">
<b>:</b>
</td>
<td width="22" style="height: 25px">
</td>
<td class="style6">
&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;<asp:CheckBoxList
ID="ChkProds" runat="server"
CssClass="fieldText">
<asp:ListItem>Stereo System</asp:ListItem>
<asp:ListItem>Laptop</asp:ListItem>
<asp:ListItem>Keyboard</asp:ListItem>
</asp:CheckBoxList>
</td>
</tr>

<tr>
<td colspan =5 align="center" fieldText" style="height: 22px"
width="173">
<asp:Button ID="btnCost" runat="server" onclick="btnCost_Click"
Text="CalculateCost" />
</td>

</tr>

<tr>
<td class="fieldText" style="height: 22px" width="173">
Cost
</td>
<td class="fieldText" style="height: 22px" width="4">
<b>:</b>
</td>
<td style="height: 22px" width="22">
</td>
<td valign="top" class="style5">

43
<asp:TextBox runat="server" name="txtCost" ID="txtCost"
class="ActiveTextBox"
MaxLength="50" ToolTip="Max limit 50" ></asp:TextBox>&nbsp;
</td>
</tr>
<tr>
<td class="fieldText" style="height: 25px" width="173">
</td>
<td class="fieldText" style="height: 25px" width="4">
</td>
<td style="height: 25px" width="22">
</td>
<td class="style6">
</td>
</tr>
</tbody>
</table>
<!--//Personal Details Section Ends Here//-->
</td>
<td style="width: 4px">
</td>
</tr>
<tr>
<td colspan="3" height="10">
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td height="48" align="center">
<asp:Button ID="btnSubmit" runat= "server" OnClick="btnSubmit_Click"
Text="Submit" />

</td>
</tr>
</table>
<br>
</td>
</tr>
</table>
</asp:Content>

Shop.aspx.cs

44
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;
namespace ShoppingChart
{
public partial class Shop : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

//DataSet ds = new DataSet();


//SqlDataAdapter selq = new SqlDataAdapter("select * from CustomerInfo", con);
//selq.Fill(ds, "CustomerInfo");
//lblmsg.Text = ds.Tables[0].Rows[0]["CustomerName"].ToString();
if (!IsPostBack)
{
if (Request["customerid"] != null)
{
hidCustomerId.Value = Request["customerid"];
BindDBValues();
}
}

protected void btnSubmit_Click(object sender, ImageClickEventArgs e)


{
}
public void InsertData()
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
con.Open();

string strprods = "";


foreach (ListItem cBox in ChkProds.Items)

45
{
if (cBox.Selected)
{
strprods += cBox.Value + " , ";
}
}

string Products = strprods;


string strsql;
strsql = "Insert into ShoppingCart(CustomerName,Cost,ProductsName)";
strsql = strsql + "values('" + txtCustomerName.Text + "',";
strsql = strsql + "'" + txtCost.Text + "','" + Products + "')";
//Response.Write(strsql);
//Response.End();
SqlCommand objsqlcomm = con.CreateCommand();

objsqlcomm.CommandText =strsql ;
objsqlcomm.ExecuteNonQuery();
}
public void UpdateData()
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
con.Open();
int CustomerId=Convert.ToInt32(hidCustomerId.Value);

string strprods = "";


foreach (ListItem cBox in ChkProds.Items)
{
if (cBox.Selected)
{
strprods += cBox.Value + " , ";
}
}

string Products = strprods;


string strsql;
strsql = "update CustomerInfo set CustomerName='" + txtCustomerName.Text + "',";
strsql = strsql + "Cost='" + Convert.ToInt32(txtCost.Text) + "',";
strsql = strsql +"Products='" + Products + "' where CustomerId=" + CustomerId + "" ;
//Response.Write(strsql);
//Response.End();
SqlCommand objsqlcomm = con.CreateCommand();

objsqlcomm.CommandText = strsql;
objsqlcomm.ExecuteNonQuery();
}
public void BindDBValues()

46
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
con.Open();

int CustomerId = Convert.ToInt32( hidCustomerId.Value);


SqlDataAdapter selq = new SqlDataAdapter("select * from CustomerInfo where CustomerId=" +
CustomerId + "", con);

DataSet ds =new DataSet() ;


selq.Fill(ds, "CustomerInfo");
if (ds != null)
{

txtCustomerName.Text = ds.Tables[0].Rows[0]["ContactNumber"].ToString();
txtCost.Text = ds.Tables[0].Rows[0]["Cost"].ToString();
//txtAddress.Text = ds.Tables[0].Rows[0]["CustomerAddress"].ToString();
// txtCustomerName.Text = ds.Tables[0].Rows[0]["CustomerName"].ToString();
// txtCompanyName.Text = ds.Tables[0].Rows[0]["CompanyName"].ToString();

string splitstr;
splitstr = ds.Tables[0].Rows[0]["ProductsName"].ToString().Trim();
string[] splitstr1 = splitstr.Split(',');

for (int i = 0;i < ChkProds.Items.Count;i++)


{
for (int j = 0; j < splitstr1.Length; j++)
{
if (ChkProds.Items[i].Text.ToString() == splitstr1[j].ToString().Trim())
{
ChkProds.Items[i].Selected = true;
}
}
}
}
}

protected void btnSubmit_Click(object sender, EventArgs e)


{
/****************Showing Simple posting of the form
*************************************

lblmsg.Text ="Selected City is "+ ddlCity.SelectedItem.Value+"<br>" ;


lblmsg.Text = lblmsg.Text + "Selected State: " + ddlState.SelectedItem.Value + "<br>";
lblmsg.Text = lblmsg.Text + "Customer Name: " + txtCustomerName.Text + "<br>";

lblmsg.Text = lblmsg.Text + "Address: " + txtAddress.Text + "<br>";


lblmsg.Text = lblmsg.Text + "Company name:" + txtCompanyName.Text + "<br>";

47
lblmsg.Text = lblmsg.Text +"Contact No:"+txtContactNum .Text+"<br>";
if (rdNoTypeMob.Checked == true)
{
lblmsg.Text = lblmsg.Text + "Number Type:" +rdNoTypeMob.Text+"<br>";
}
else
{
lblmsg.Text = lblmsg.Text + "Number Type:" + rdNoTypePh.Text + "<br>";
}
string strdepts = "";
foreach(ListItem cBox in ChkDepts.Items) {
if(cBox.Selected) {
strdepts += cBox.Value + " / ";
}
}

lblmsg.Text = lblmsg.Text+ "Selected Departments are "+strdepts;


**************************************************************************/
if (hidCustomerId.Value != "")
{
UpdateData();
}
else
{
InsertData();

}
Response.Redirect("CustomerList.aspx");

protected void btnCost_Click(object sender, EventArgs e)


{
int strprods=0;
int Sts = 2000;
int Lpt = 50000;
int Kb = 200;
foreach (ListItem cBox in ChkProds.Items)
{
if (cBox.Selected)
{
if (cBox.Value == "Stereo System")
{
strprods += Sts;
}
if (cBox.Value == "Laptop")
{
strprods += Lpt;

48
}
if (cBox.Value == "Keyboard")
{
strprods += Kb;
}

}
txtCost.Text = strprods.ToString() ;
}

}
}

CustomerList.aspx

<%@ Page Language="C#" MasterPageFile="~/Menu.Master" AutoEventWireup="true"


CodeBehind="CustomerList.aspx.cs" Inherits="ShoppingChart.CustomerList" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<script type="text/javascript" language="javascript">


function DeleteConfirmation()
{
if (confirm("Are you sure,you want to delete selected records ?")==true)
return true;
else
return false;
}
</script>
<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">

<tr>
<td valign="top" width="74%" ><table width="90%" border="0" align="center" cellpadding="0"
cellspacing="0">
<tr>
<td class="TextHead" style="height: 21px">Customer Details </td>
</tr>
<tr>
<TD colSpan=3 style="height: 10px">
&nbsp; &nbsp; <asp:Label ID="lblmsg" name = "lblmsg" CssClass="Normal" ForeColor="Red"
runat="server" Width="325px"></asp:Label>

49
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
&nbsp;&nbsp;</TD>
</tr>
</td>
</tr>
<tr>
<td>
<asp:GridView runat = "server" ID="gvListCustomer" DataKeyNames="CustomerId"
name="gvListCustomer" AllowPaging ="True" CssClass="grid"
AutoGenerateColumns="False" Width = "100%" align="center"
OnRowCommand="gvListCust_RowCommand"
OnPageIndexChanging="gvListCust_PageIndexChanging"
onsorting="gvListCustomer_Sorting" AllowSorting ="true" PageSize="10" >
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText ="CustomerId"
SortExpression="CustomerId" Visible = "true"/>
<asp:BoundField DataField="ProductsName" HeaderText ="ProductsName"
SortExpression="ProductsName" />
<asp:BoundField DataField="Cost" HeaderText ="Cost"
SortExpression="Cost" />
<asp:BoundField DataField="CustomerName" HeaderText ="CustomerName"
SortExpression="CustomerName" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton cssclass= "editlink" ID="EditCustlink" Text="Edit" runat="server"
CausesValidation="False" CommandName="EditCustomer" CommandArgument='<
%#DataBinder.Eval(Container, "DataItem.CustomerId")%>' ></asp:LinkButton>
</ItemTemplate>

<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
<HeaderTemplate>
<asp:Button ID="btnDelete" runat="server" Text="Delete"
OnClick="btnDelete_Click"
OnClientClick="return DeleteConfirmation();"/>
</HeaderTemplate>

</asp:TemplateField>

</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td colspan="4" style="border-bottom:1ps dotted #333333; height: 5px;">&nbsp;</td>
</tr>

50
<tr>
<td height="48" align="center"><a href="CustomerMaster.aspx"><img src="../Images/btn-
createnew.gif" " width="87" height="25" border="0"></a></td>
</tr>
</table>

<br></td>
</tr>

</table>
</asp:Content>

CustomerList.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;
namespace ShoppingChart
{
public partial class CustomerList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["SortExpression"] = "CustomerName";
ViewState["SortDirection"] = "Asc";
BindGridview();
}
}

protected void gvListCust_PageIndexChanging(object sender, GridViewPageEventArgs e)


{
gvListCustomer.PageIndex = e.NewPageIndex;
BindGridview();

51
}

protected void gvListCust_RowCommand(object sender, GridViewCommandEventArgs e)


{
Session["Operation"] = "EditCustomer";
if (e.CommandName == "EditCustomer")
{
int CustomerId = Convert.ToInt32(e.CommandArgument.ToString());
Response.Redirect("CustomerMaster.aspx?customerid=" + CustomerId);
}
}
public void BindGridview()
{

SqlConnection con = new


SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
con.Open();
SqlDataAdapter selq = new SqlDataAdapter("select * from ShoppingCart ", con);

DataSet dsadList = new DataSet();


selq.Fill(dsadList, "ShoppingCart");

DataView dv;

dv = dsadList.Tables[0].DefaultView;

if (ViewState["SortExpression"] != null)

dv.Sort = Convert.ToString(ViewState["SortExpression"]) + " " +


Convert.ToString(ViewState["SortDirection"]);
gvListCustomer.DataSource = dv;
gvListCustomer.DataBind();
}

protected void gvListCustomer_Sorting(object sender, GridViewSortEventArgs e)


{
ViewState["SortExpression"] = e.SortExpression;
if (Convert.ToString(ViewState["SortDirection"]).Trim() != "Desc")
ViewState["SortDirection"] = "Desc";
else
ViewState["SortDirection"] = "Asc";
BindGridview();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
string ids = null;

52
for (int i = 0; i < gvListCustomer.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)gvListCustomer.Rows[i].Cells[0].FindControl("chkSelect");

if (chkDelete.Checked)
{
ids = ids + "," + Convert.ToInt32(gvListCustomer.Rows[i].Cells[0].Text);

}
ids = ids.Substring(1, ids.Length - 1);
delete(ids);

}
public void delete(string ids)
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
con.Open();
string strsql;
strsql = "Delete from ShoppingCart WHERE CustomerId in (" + ids + ")";
SqlCommand objsqlcomm = con.CreateCommand();

objsqlcomm.CommandText = strsql;
objsqlcomm.ExecuteNonQuery();
BindGridview();

}
}
}

53
OUTPUT:

54
55
6. Database Connectivity For Student Information:

Insert Student Data.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 id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
<p>
<asp:Label ID="Label1" runat="server"
style="z-index: 1; left: 241px; top: 140px; position: absolute; height: 19px"
Text="Student Roll No"></asp:Label>
</p>
<asp:Label ID="Label2" runat="server"
style="z-index: 1; left: 234px; top: 188px; position: absolute"
Text="Student Name"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"
style="z-index: 1; left: 397px; top: 140px; position: absolute"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"
style="z-index: 1; left: 398px; top: 181px; position: absolute"></asp:TextBox>
<asp:Label ID="Label3" runat="server"
style="z-index: 1; left: 246px; top: 230px; position: absolute"
Text="Course"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server"
style="z-index: 1; left: 395px; top: 225px; position: absolute"></asp:TextBox>
<asp:Label ID="Label4" runat="server"
style="z-index: 1; left: 246px; top: 271px; position: absolute"
Text="Address"></asp:Label>
<asp:TextBox ID="TextBox4" runat="server"
style="z-index: 1; left: 397px; top: 273px; position: absolute"></asp:TextBox>
<p>
<asp:Button ID="Button1" runat="server"
style="z-index: 1; left: 397px; top: 326px; position: absolute"
Text="Add Student" onclick="Button1_Click" />
</p>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
style="z-index: 1; left: 606px; top: 323px; position: absolute" Text="View" />
</form>
</body>
</html>

56
Insert Student Data.cs:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page


{
public System.Data.SqlClient.SqlConnection con;
public System.Data.SqlClient.SqlCommand cmd;
public System.Data.SqlClient.SqlDataReader rd;

protected void Page_Load(object sender, EventArgs e)


{
//con = new SqlConnection("workstation id=ACER8;Initial Catalog=student Info;user id=sa;Data
Source=ACER8");
//con = new SqlConnection("workstation id=ACER8;Integrated Security=SSPI;Persist Security Info=False;User
ID=sa;Initial Catalog=student Info;Data Source=ACER8");
//con=new SqlConnection(" Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and
Settings\Shrenik\My Documents\Visual Studio
2005\WebSites\StudentInformation\App_Data\App_Data\Database1.mdf;Integrated Security=True;User
Instance=True");
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
con.Open();

}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);

con.Open();
cmd = new SqlCommand("insert into student (rollno,name,course,address) values (" +
Convert.ToInt16(TextBox1.Text) + ",'" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Student data inserted");

}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("view.aspx");
}
}

57
View .aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="view.aspx.cs"
Inherits="view" %>

<!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 id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
<asp:GridView ID="GridView1" runat="server"

style="z-index: 1; left: 289px; top: 138px; position: absolute;


height: 133px; width: 187px">
</asp:GridView>
</form>
</body>
</html>

View .cs:

using System;
using System.Collections;
using System.Configuration;
using System.Data;

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.Data.SqlClient;

public partial class view : System.Web.UI.Page


{
public System.Data.SqlClient.SqlConnection con;
public System.Data.SqlClient.SqlDataAdapter adpt;
public DataSet ds = new DataSet();

protected void Page_Load(object sender, EventArgs e)


{
// con = new SqlConnection("workstation id=ACER8;Integrated
Security=SSPI;Persist Security Info=False;User ID=sa;Initial Catalog=student
Info;Data Source=ACER8");
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);

58
con.Open();
adpt = new SqlDataAdapter("select * from student", con);
adpt.Fill(ds, "student");
GridView1.DataSource = ds.Tables["student"];
GridView1.DataBind();
con.Close();
}
}

Output:

59
60
61

You might also like