Tuesday, 29 July 2014

How to use DataReader in ASP.NET

DataReader example: how to use DataReader in asp.net

  1. <%@ Page Language=“C#” %>
  2. <%@ Import Namespace=“System.Data” %>
  3. <%@ Import Namespace=“System.Data.SqlClient” %>
  4. <%@ Import Namespace=“System.Configuration” %>

  5. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

  6. <script runat=“server”>
  7.     protected void Page_Load(object sender, System.EventArgs e) {
  8.         if (!Page.IsPostBack) {
  9.             SqlConnection MyConnection;
  10.             SqlCommand MyCommand;
  11.             SqlDataReader MyReader;

  12.             MyConnection = new SqlConnection();
  13.             MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings["AppConnectionString1"].ConnectionString;

  14.             MyCommand = new SqlCommand();
  15.             MyCommand.CommandText = “SELECT TOP 10 * From PRODUCTS”;
  16.             MyCommand.CommandType = CommandType.Text;
  17.             MyCommand.Connection = MyConnection;

  18.             MyCommand.Connection.Open();
  19.             MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);

  20.             GridView1.DataSource = MyReader;
  21.             GridView1.DataBind();

  22.             MyCommand.Dispose();
  23.             MyConnection.Dispose();
  24.         }
  25.     }
  26. </script>

  27. <html xmlns=“http://www.w3.org/1999/xhtml”>
  28. <head runat=“server”>
  29.     <title>DataReader example: how to use DataReader in asp.net</title>
  30. </head>
  31. <body>
  32.     <form id=“form1″ runat=“server”>
  33.     <div>
  34.         <asp:GridView ID=“GridView1″ runat=“server”>
  35.         </asp:GridView>
  36.     </div>
  37.     </form>
  38. </body>
  39. </html>

No comments:

Post a Comment