SQL SELECT Command with parameters

(ASP.NET)


Hi,
In this article i discuss about how to fetch records from database by using sql select command with parameters in ado.net.

.aspx

<div>
        <asp:Button ID="btn_commandwithparam" runat="server" OnClick="btn_commandwithparam_Click" Text="Sql Command with Parameters" /> &nbsp;&nbsp;
  <br />
        <br />
        <asp:GridView ID="grdvw_products" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
            <AlternatingRowStyle BackColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#EFF3FB" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F5F7FB" />
            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
            <SortedDescendingCellStyle BackColor="#E9EBEF" />
            <SortedDescendingHeaderStyle BackColor="#4870BE" />
        </asp:GridView>
<br/>
<br/>
</div>


Code behind:-

   protected void btn_commandwithparam_Click(object sender, EventArgs e)
        {
            try
            {
                sqlcommandwithParameters();
            }
            catch (Exception)
            { }

        }

  //sql command with parameters
        private void sqlcommandwithParameters()
        {
            try
            {
                using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["adodotnetConstring"].ToString()))
                {
                    string sql = "SELECT * FROM Products WHERE CategoryID=@Categoryid";
                    using (SqlCommand cmd = new SqlCommand(sql, con))
                    {
                        cmd.Parameters.Add("@Categoryid", SqlDbType.Int);
                        cmd.Parameters["@Categoryid"].Value = 2;
                        SqlDataReader rdr;
                        con.Open();
                        rdr = cmd.ExecuteReader();
                      
                        grdvw_products.DataSource = rdr;
                        grdvw_products.DataBind();
                        rdr.Close();
                        con.Close();
                    }
                }
            }
            catch (Exception)
            { }
        }

Image

Ratings


Average Rating: 0.00 by 0 users
Giri Prasad
7/21/2013
7/21/2013
Download PDF

Comments