Thursday, 27 June 2013

How to Get all Information SQL Server in ASP .NET

How to Get all Information SQL Server in ASP .NET

Step 1. Drag a text Box and a Button control on your page. Default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  
Codevirtual="Default.aspx.cs" Inherits="_Default" %>
<%@ Register assembly="AjaxControlToolkit" 
namespace="AjaxControlToolkit" tagprefix="cc1" %>
<!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>
    <table><tr>
    <td>Enter the ID:</td><td>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td><td>
    <asp:Label ID="Label1" runat="server"></asp:Label>
    </td></tr>
    <tr><td>
    <asp:Button ID="Button1" runat="server" Text="Submit" 
	onclick="Button1_Click" /></td></tr>
    </table>
    </div>
   
    </form>
</body>
</html>
Step 2. Default.aspx.cs Code

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page 
{
  SqlConnection newConnection = new SqlConnection(@"Data 
  Source=R4R-3EFD13BB468\SQLEXPRESS;
  initial catalog=newDatabase;integrated security=true;");
  protected void Page_Load(object sender, EventArgs e)
  { 
  }
  protected void Button1_Click(object sender, EventArgs e)
  {
  newConnection.Open();
  SqlCommand cmd = new SqlCommand("select age,nme from emp_tbl where emp_id=@id",
  newConnection);
  cmd.Parameters.AddWithValue("@id", TextBox1.Text);
  SqlDataReader dr = cmd.ExecuteReader();
  if (dr.Read())
  {
  Label1.Text = "Employee Name: " + dr["nme"].ToString() + 
  " and Your age is " + dr["age"].ToString();
  }
  else
  {
  Label1.Text = "Enter Correct Emp ID";
  }
  }
}

Step 3. Run the Application.

No comments: