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.- <%@ Page Language=“C#” %>
- <%@ Import Namespace=“System.Data” %>
- <%@ Import Namespace=“System.Data.SqlClient” %>
- <%@ Import Namespace=“System.Configuration” %>
- <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
- <script runat=“server”>
- protected void Page_Load(object sender, System.EventArgs e) {
- if (!Page.IsPostBack) {
- SqlConnection MyConnection;
- SqlCommand MyCommand;
- SqlDataReader MyReader;
- SqlParameter ProductNameParam;
- MyConnection = new SqlConnection();
- MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings["AppConnectionString1"].ConnectionString;
- MyCommand = new SqlCommand();
- MyCommand.CommandText = “SELECT * FROM PRODUCTS WHERE PRODUCTNAME = @PRODUCTNAME”;
- MyCommand.CommandType = CommandType.Text;
- MyCommand.Connection = MyConnection;
- ProductNameParam = new SqlParameter();
- ProductNameParam.ParameterName = “@PRODUCTNAME”;
- ProductNameParam.SqlDbType = SqlDbType.VarChar;
- ProductNameParam.Size = 25;
- ProductNameParam.Direction = ParameterDirection.Input;
- ProductNameParam.Value = “CHAI”;
- MyCommand.Parameters.Add(ProductNameParam);
- MyCommand.Connection.Open();
- MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);
- GridView1.DataSource = MyReader;
- GridView1.DataBind();
- MyCommand.Dispose();
- MyConnection.Dispose();
- }
- }
- </script>
- <html xmlns=“http://www.w3.org/1999/xhtml”>
- <head runat=“server”>
- <title>SqlParameter example: how to use SqlParameter in asp.net</title>
- </head>
- <body>
- <form id=“form1″ runat=“server”>
- <div>
- <asp:GridView ID=“GridView1″ runat=“server”>
- </asp:GridView>
- </div>
- </form>
- </body>
- </html>

No comments:
Post a Comment