Thursday, 16 July 2015

Get data from SQL Table to C#.Net application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;


namespace WebApplication1
{
    public partial class Home : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnGetData_Click(object sender, EventArgs e)
        {
            string connectionString = @"Data Source=NAVI-PC;Initial Catalog=Northwind;User ID=sa;Password=password";
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                
                con.Open();

                using (SqlCommand command = new SqlCommand("select EmployeeID,LastName,FirstName,Title,BirthDate from employees where EmployeeID=" + txtEmpID.Text, con))
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        while (reader.Read())
                        {
                            txtFirstName.Text = reader["LastName"].ToString();
                            txtLastName.Text = reader["FirstName"].ToString();
                            txtTitle.Text = reader["Title"].ToString();
                            txtDOB.Text = reader["BirthDate"].ToString();

                            lblMessage.Text = "Data received successfully...";
                        }

                        
                    }
                    else
                    {
                        lblMessage.Text = "No Data found";
                    }
                }
            }
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            txtDOB.Text = string.Empty;
            txtEmpID.Text = string.Empty;
            txtFirstName.Text = string.Empty;
            txtLastName.Text = string.Empty;
            txtTitle.Text = string.Empty;

            lblMessage.Text = "Please enter new EmployeeID";
        }
    }
}