Tuesday, February 14, 2012

Fetch data from Sql Server using AJAX in ASP.Net



Fetch and display data using AJAX



Step 1)Open a ASP.Net AJAX enable website in your visual Studio .

Step 2)Add below code in your ASP.net page.

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

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
       
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                Enter username:-<asp:TextBox ID="TextBox2" runat="server" Width="134px"></asp:TextBox>&nbsp;
                <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Password" />
                &nbsp; &nbsp;<asp:Label ID="Label1" runat="server" Width="156px"></asp:Label>
                &nbsp; &nbsp; &nbsp;<br />
            </ContentTemplate>
        </asp:UpdatePanel>
       
   
    </div>
    </form>
</body>
</html>

Step 3) Add below code into your code behind page.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;


public partial class check_user : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    SqlDataReader rd;
    public string query;

    protected void connection()
    {
        con.ConnectionString = "server=.\\SQLEXPRESS; integrated security=SSPI; initial catalog=sourav;";
        con.Open();
        cmd.Connection = con;

    }

    protected void Page_Load(object sender, EventArgs e)
    {
        connection();

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        string user=this.TextBox2.Text.ToString();
        cmd.CommandText = "select * from loginfo where username='"+user+"'";
        rd = cmd.ExecuteReader();
        if (rd.Read())
        {
            this.Label1.Text = rd.GetSqlValue(1).ToString();
           
        }
        rd.Close();
    }
}

N.B:-Change databaseserver name , database name and table name in code.

1 comment: