Tuesday, 29 July 2014

How to use SqlParameter in asp.net

SqlParameter example: how to use SqlParameter in asp.net
Create a web form name SqlParameterExample.aspx. Now add a GridView control. We populate the GridView control with SqlDataSource Data. But here we filter the data by SqlParameter. In this example we select the NorthWind database Products table data and filter it with SqlParameter product name. The source code of SqlParameterExample.aspx is here.

  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.             SqlParameter ProductNameParam;

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

  15.             MyCommand = new SqlCommand();
  16.             MyCommand.CommandText = “SELECT * FROM PRODUCTS WHERE PRODUCTNAME = @PRODUCTNAME”;
  17.             MyCommand.CommandType = CommandType.Text;
  18.             MyCommand.Connection = MyConnection;

  19.             ProductNameParam = new SqlParameter();
  20.             ProductNameParam.ParameterName = “@PRODUCTNAME”;
  21.             ProductNameParam.SqlDbType = SqlDbType.VarChar;
  22.             ProductNameParam.Size = 25;
  23.             ProductNameParam.Direction = ParameterDirection.Input;
  24.             ProductNameParam.Value = “CHAI”;

  25.             MyCommand.Parameters.Add(ProductNameParam);

  26.             MyCommand.Connection.Open();
  27.             MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);

  28.             GridView1.DataSource = MyReader;
  29.             GridView1.DataBind();

  30.             MyCommand.Dispose();
  31.             MyConnection.Dispose();
  32.         }
  33.     }
  34. </script>

  35. <html xmlns=“http://www.w3.org/1999/xhtml”>
  36. <head runat=“server”>
  37.     <title>SqlParameter example: how to use SqlParameter in asp.net</title>
  38. </head>
  39. <body>
  40.     <form id=“form1″ runat=“server”>
  41.     <div>
  42.         <asp:GridView ID=“GridView1″ runat=“server”>
  43.         </asp:GridView>
  44.     </div>
  45.     </form>
  46. </body>
  47. </html>

No comments:

Post a Comment