Sunday 5 May 2013

C# Ado.Net Sql Parameter Example

C# Ado.Net Sql Parameter Example:-

.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Params.aspx.cs" Inherits="Params" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /><br />
        <br />
        <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
            <AlternatingRowStyle BackColor="White" />
            <EditRowStyle BackColor="#7C6F57" />
            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#E3EAEB" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F8FAFA" />
            <SortedAscendingHeaderStyle BackColor="#246B61" />
            <SortedDescendingCellStyle BackColor="#D4DFE1" />
            <SortedDescendingHeaderStyle BackColor="#15524A" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>


.cs

  protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand("select * from SampleData where Id = @Id", con))
                {
                    SqlParameter param1 = new SqlParameter("@Id", TextBox1.Text);
                    cmd.Parameters.Add(param1);
                    SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    GridView1.DataSource = reader;
                    GridView1.DataBind();
                }
            }
        }
        catch (Exception error)
        {
            Page.Response.Write("Error on page");
        }
    }
}