Friday 22 November 2013

Repeater/Gridview for Web Application

Repeator
 on page behind-----:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ShowDetailsInRepeater.aspx.cs" Inherits="GarageDetails.ShowDetailsInRepeater" %>

<!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>
    <center>
    `<table cellpadding="0" cellspacing="0" border="0" width="100%">
    <tr>
    <td>
    <asp:Label ID="lblRepFirstName" runat="server" Text="Enter The Name"></asp:Label>
    </td>
    <td>
    <asp:TextBox ID="txtRepFirstName" runat="server"
            ontextchanged="txtRepFirstName_TextChanged">
    </asp:TextBox>
    </td>
    </tr>
    <asp:Repeater id="GetGarageDetails" runat="server"
            >

<HeaderTemplate>
<table border="1" width="100%">
<tr>
<th>CustomerId</th>
<th>FirstName</th>
<th>LastName</th>
<th>ContactNumber</th>
<th>VehicleName</th>
<th>ChesisNumber</th>
<th>EngineNumber</th>
<th>RegistrationNumber</th>
</tr>
</HeaderTemplate>

<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblCustomerId" runat="server" Text='<%# Eval("CustomerId")  %>'></asp:Label>
</td>
<td>
<asp:Label ID="lblFirstName" runat="server" Text='<%#Eval("FirstName") %>'></asp:Label>
</td>
<td>
<asp:Label ID="lblLastName" runat="server" Text='<%#Eval("LastName") %>'></asp:Label>
</td>
<td>
<asp:Label ID="lblContactNumber" runat="server" Text='<%#Eval("ContactNumber") %>'></asp:Label>
</td>
<td>
<asp:Label ID="lblVehicleName" runat="server" Text='<%#Eval("VehicleName") %>'></asp:Label>
</td>
<td>
<asp:Label ID="lblEngineNumber" runat="server" Text='<%#Eval("EngineNumber") %>'></asp:Label>
</td>
<td>
<asp:Label ID="lblChesisNumber" runat="server" Text='<%#Eval("ChesisNumber") %>'></asp:Label>
</td>
<td>
<asp:Label ID="lblRegistrationNumber" runat="server" Text='<%#Eval("RegistrationNumber") %>'></asp:Label>
</td>
</tr>
</ItemTemplate>

<FooterTemplate>
</table>
</FooterTemplate>

</asp:Repeater>
   
   
   
   
    </table>
    </center>
    </div>
    </form>
</body>
</html>
---------------------------------------
                                    OR
Grid 
Page Behing Code:-

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="grid.aspx.cs" Inherits="VehicleManagementSystem.grid" %>

<!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>
    <table  border="0" cellpadding="0" cellspacing="0">
    <tr>
    <td>
    <asp:Label ID="lblName" runat="server" Text="Enter the name to be searched"></asp:Label>
    </td>
    <td>
    <asp:TextBox ID="txtName" runat="server" ontextchanged="txtName_TextChanged" AutoPostBack="true"></asp:TextBox>
    </td>
    </tr>

    </table>
   
    <asp:GridView ID="GridForData" runat="server" AutoGenerateColumns="false">

    <Columns>
    <asp:BoundField DataField="OwnerId" HeaderText="OwnerId"/>
 
    <asp:BoundField DataField="OwnerFirstName" HeaderText="FirstName"/>
    <asp:BoundField DataField="OwnerMiddleName" HeaderText="MiddleName"/>
    <asp:BoundField DataField="OwnerLastName" HeaderText="LastName" />
    <asp:BoundField DataField="VehicalName" HeaderText="VehicalName"/>
    <asp:BoundField DataField="VehicalNo" HeaderText="VehicalNo"/>
    <asp:BoundField DataField="ChechisNo" HeaderText="ChechisNo"/>
   
    </Columns>

    </asp:GridView>
    </div>
    </form>
</body>

</html>


-----------------------------------------

DAL Page :-


 public DataTable GetOwnerDetailsForGridview(string OwnerFirstName)
        {
            SqlConnection con = new SqlConnection(Setting.ConnectionString);
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "usp_GetOwnerDetailsForGridview";
            cmd.Parameters.AddWithValue("OwnerFirstName", OwnerFirstName);
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);

            DataTable dt = ds.Tables[0];
            return dt;
        }

---------------------------------
ON Page:-

 protected void txtOwnersFirstName_TextChanged(object sender, EventArgs e)
        {
            string OwnerFirstName = txtOwnersFirstName.Text;
            VehicalDetailsDAL vehicalsDetailsDAL = new VehicalDetailsDAL();
            RepeaterForData.DataSource =            vehicalsDetailsDAL.GetOwnerDetailsForGridview(OwnerFirstName);
            RepeaterForData.DataBind();
        }

Store Procedure..............

Function:-

Function is mainly used in the case where it must return a value. Where as a procedure may or may not return a value or may return more than one value using the OUT parameter.

Function can be called from SQL statements where as procedure can not be called from the sql statements

Functions are normally used for computations where as procedures are normally used for executing business logic.

You can have DML (insert,update, delete) statements in a function. But, you cannot call such a function in a SQL query.

Function returns 1 value only. Procedure can return multiple values (max 1024).

Stored Procedure: supports deferred name resolution. Example while writing a stored procedure that uses table named tabl1 and tabl2 etc..but actually not exists in database is allowed only in during creation but runtime throws error Function wont support deferred name resolution.


Stored procedure:-

Stored procedure returns always integer value by default zero. where as function return type could be scalar or table or table values

Stored procedure is precompiled execution plan where as functions are not.

A procedure may modify an object where a function can only return a value The RETURN statement immediately completes the execution of a subprogram and returns control to the caller.




Create Table:-

Create Table OwnerDetails (OwnerId int Identity(1,1) Primary Key, OwnerFirstName nvarchar(255), OwnerMiddleName nvarchar(255), OwnerLastName nvarchar(255));

Create Table VehicalDetails (VehicalId int identity(1,1) Primary Key, OwnerId int Foreign Key References OwnerDetails(OwnerId))

Alter Table VehicalDetails Add VehicalName nvarchar(255), ChechisNo int, VehicalNo nvarchar(255)

---------------
Writting Procedure:-

 To Insert
Create Proc usp_AddOwnerDetails
@OwnerFirstName nvarchar(255),
@OwnerMiddleName nvarchar(255),
@OwnerLastName nvarchar(255)
as begin
insert into OwnerDetails(OwnerFirstName,OwnerMiddleName,OwnerLastName)Values(@OwnerFirstName,@OwnerMiddleName,@OwnerLastName)
Select Scope_Identity( )
end
-----------------------------

 To Update

Create Proc usp_UpdateOwnerDetails
@OwnerFirstName nvarchar(255),
@OwnerMiddleName nvarchar(255),
@OwnerLastName nvarchar(255),
@OwnerId int
as begin
Update OwnerDetails set OwnerFirstName=@OwnerFirstName,OwnerMiddleName=@OwnerMiddleName,OwnerLastName=@OwnerLastName where OwnerId=@OwnerId
end

-----------------------------------
 ToDelete

Create Proc usp_DeleteOwnerDetails
@OwnerId int
as begin
Delete From OwnerDetails where OwnerId=@OwnerId
end

------------------------------------------
 To Search

Create Proc usp_SearchOwnerDetails
@OwnerId int
as begin
Select* From OwnerDetails where OwnerId=@OwnerId
end


----------------------------------
 To GridView:-
SP for GridView By FirstName:-

Create proc usp_GetOwnerDetailsForGridview
@OwnerFirstName nvarchar(255)
as
begin
Select o.OwnerId,o.OwnerFirstName,o.OwnerMiddleName,o.OwnerLastName,v.VehicalName,v.VehicalNo,v.ChechisNo from OwnerDetails o inner join VehicalDetails v on v.OwnerId=o.OwnerId where o.OwnerFirstName like '%'+@OwnerFirstName+'%'
end

----------------------

Thursday 14 November 2013

Code For DAL, BAL & Code At ASPX Page..

   Code to Create Connection String Page:

-------------------------------------

DAL Code:-

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

namespace VehicleManagement
{
    public class VehicalDetailsDAL
    {
        public int VehicalDetailsId { get; set; }
        public int OwnerId { get; set; }
        public string VehicalName { get; set; }
        public string ChechisNo { get; set; }
        public string VehicalNo { get; set; }

        SqlConnection conn = new SqlConnection(Setting.ConnectionString);
---------------------------------------------------------------------------------------------------
To Insert:-


        public int AddVehical(VehicalDetailsDAL vehicalDetailsDAL)
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "usp_VehicalDetails";
            cmd.Parameters.AddWithValue("@VehicalDetailsId", vehicalDetailsDAL.VehicalDetailsId);
            cmd.Parameters.AddWithValue("@OwnerDetailsId", vehicalDetailsDAL.OwnerId);
            cmd.Parameters.AddWithValue("@VehicalName", vehicalDetailsDAL.VehicalName);
            cmd.Parameters.AddWithValue("@ChechisNo", vehicalDetailsDAL.ChechisNo);
            cmd.Parameters.AddWithValue("@VehicalNo", vehicalDetailsDAL.VehicalNo);

            int VehicalDetailsId = Convert.ToInt16(cmd.ExecuteScalar());
            conn.Close();
            return VehicalDetailsId;

        }
---------------------------------------------------------------------------------------------------
To Delete:-

        public void DeleteVehical(int VehicalDetailsId)
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "usp_DeleteVehicalDetails";
            cmd.Parameters.AddWithValue("@VehicalDetailsId", VehicalDetailsId);
            cmd.ExecuteNonQuery();
            conn.Close();

        }
---------------------------------------------------------------------------------------------------
To Search:-

        public VehicalDetailsDAL SearchOwnerDetails(int VehicalDetailsId)
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "usp_SearchVehicalDetails";
            SqlDataReader dr = cmd.ExecuteReader();
            VehicalDetailsDAL v = new VehicalDetailsDAL();
            while (dr.Read())
            {
                v.VehicalDetailsId = Convert.ToInt16(dr["VehicalDetailsId"]);
                v.OwnerId = Convert.ToInt16(dr["OwnerDetailsId"]);
                v.VehicalName = dr["VehicalName"].ToString();
                v.ChechisNo = dr["ChechisNo"].ToString();
                v.VehicalNo = dr["VehicalNo"].ToString();
            }
            conn.Close();
            return v;

        }
---------------------------------------------------------------------------------------------------
To Update:-

        public void UpdateVehicalDetails(VehicalDetailsDAL vehicalDetailsDAL)
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "usp_UpdateVehicalDetails";
            cmd.Parameters.AddWithValue("@VehicalDetailsId", vehicalDetailsDAL.VehicalDetailsId);
            cmd.Parameters.AddWithValue("@OwnerDetailsId", vehicalDetailsDAL.OwnerId);
            cmd.Parameters.AddWithValue("@VehicalName", vehicalDetailsDAL.VehicalName);
            cmd.Parameters.AddWithValue("@ChechisNo", vehicalDetailsDAL.ChechisNo);
            cmd.Parameters.AddWithValue("@VehicalNo", vehicalDetailsDAL.VehicalNo);
            cmd.ExecuteNonQuery();
            conn.Close();

       }
---------------------------------------------------------------------------------------------------

        }

}




     

------------------------------ BAL------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VehicleManagement;

namespace VehicalManagementBAL
{
    public class OwnerDetailsBAL
    {
        public string AddOwnerBAL(OwnerDetailsDAL ownerDetailsDAL)
        {
            if (string.IsNullOrEmpty(ownerDetailsDAL.OwnerFirstName))
            {
                throw new Exception("OwnerFirstName can not be Empty");

            }

            if (string.IsNullOrEmpty(ownerDetailsDAL.OwnerMiddleName))
            {
                throw new Exception("ownerMiddleName can not be empty");
            }

            if (string.IsNullOrEmpty(ownerDetailsDAL.OwnerLastName))

            {
                throw new Exception("ownerLastName can not be Empty");
            }
                 return ownerDetailsDAL.AddOwner(ownerDetailsDAL).ToString ();
        }


 

-----------------------------------------------------
 public DataSet SerachUserRecord(string txtFirstName)
     
 {
         
 SqlConnection con = new SqlConnection(Setting.ConnectionString);

 string query = "Select u.FirstName,p.ContactNumber,e.UserEmailId from UserInformation u inner join PhoneNumber p on u.UserId=p.UserId inner join EmailId e on p.UserId=e.UserId where u.FirstName='txtSearch.Text%'";
         
con.Open();
         
SqlCommand cmd = new SqlCommand(query, con);
         
cmd.Parameters.AddWithValue("@txtFirstName", txtFirstName);
         
       
  DataSet ds = new DataSet();
         
SqlDataAdapter da = new SqlDataAdapter(cmd);

         
 da.Fill(ds);
         
         
 if (ds.Tables[0].Rows.Count > 0)
            {
             
UserInformationDal userinfo = new UserInformationDal();
             
 userinfo.FirstName = ds.Tables[0].Rows[0]["FirstName"].ToString();
             
 userinfo.ContactNumber = ds.Tables[0].Rows[0]["ContactNumber"].ToString();
             
 userinfo.UserEmailId = ds.Tables[0].Rows[0]["UserEmailId"].ToString();
             
         
 }

         
con.Close();
         
 return ds;





---------------------------------------

Aspx-



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VehicleManagement;
using VehicalManagementBAL;

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

        }

        protected void btnSaveDetails_Click(object sender, EventArgs e)
        {
            VehicalDetailsDAL vehicalDetailsDAL = new VehicalDetailsDAL();

            vehicalDetailsDAL.VehicalName = txtVehicleName.Text;
            vehicalDetailsDAL.VehicalNo = txtVehicleNo.Text;
            vehicalDetailsDAL.ChechisNo = txtChechsisNo.Text;
            lblMessage.Text = "Added successfully ";
         

         
        }
    }
}
--------------------------------------



Code for Test Case.....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AddressBookBal;  
using AddressBookDal;
using NUnit.Framework;

namespace TestAddressBook
{
    [TestFixture]
    class TestUserInformation
    {
        [TestCase]
        public void TestAddNewUser()
        {  
            UserInformationBal userbal=new UserInformationBal();
            UserInformationDal userInformationDal=new UserInformationDal();
            userInformationDal.Title = "Mr";
            userInformationDal.FirstName="Ajay";
            userInformationDal.MiddleName = "ramesh";
            userInformationDal.LastName = "Sonkul";
            userInformationDal.Age = 30;
            userInformationDal.DateOfBirth = DateTime.Now;
            userInformationDal.Sex = "Male";
            userInformationDal.Category = "Family";

            String UserId = userbal.AddUserInformation(userInformationDal);
               
                UserInformationDal user = userbal.GetUserInfoById(UserId);
                if (user.Title == userInformationDal.Title && user.FirstName == userInformationDal.FirstName && user.MiddleName == userInformationDal.MiddleName && user.LastName == userInformationDal.LastName && user.Age == userInformationDal.Age && user.DateOfBirth == userInformationDal.DateOfBirth && user.Sex == userInformationDal.Sex && user.Category == userInformationDal.Category)
            {
                Assert.IsTrue(true);
            }
            else
            {
             //   userbal.GetUserInfoById(UserId);
                Assert.IsTrue(false);
           
            }

    }
        [TestCase]
        public void TestDeleteUser()
        {
            UserInformationBal userinfobal=new UserInformationBal();
            UserInformationDal userinfodal=new UserInformationDal();
            userinfodal.UserId = 24;
            userinfobal.DeleteUserInformation(userinfodal.UserId);
            UserInformationDal user= userinfobal.GetUserInfoById(userinfodal.UserId.ToString());
            if(userinfodal.UserId==user.UserId)
            {
                Assert.IsTrue(false);
            }  
            else
            {
                Assert.IsTrue(true);
            }
        }
        [TestCase]
        public void TestUpdateUser()
        {
            UserInformationDal userdal=new UserInformationDal();
            UserInformationBal userbal=new UserInformationBal();
           
            userdal.Title = "Ms";
            userdal.FirstName = "Pooja";
            userdal.MiddleName = "Sumit";
            userdal.LastName = "Mishra";
            userdal.Age = 22;
            userdal.DateOfBirth = DateTime.Now;
            userdal.Sex = "FeMale";
            userdal.Category = "Family";
            userdal.UserId = 42;

            userbal.UpdateInfo(42);
        }
    }
}

Query For Report, & Query for Insert, Update & SQL Store Procedure

Query For  Report:

SELECT        Patient_Visit.Patient_Id, Patient_Visit.Surname, Patient_Visit.Firstname, Patient_Visit.Middlename, Patient_Visit.Sex, Patient_Visit.Contact_no,
                         Patient_Details.Date_of_visit, Patient_Details.Date_of_discharge, Patient_Details.Symptoms, Patient_Details.Disease, Patient_Details.Treatment,
                         Patient_Details.DoctorName, Patient_Details.Age, Patient_Details.Occupation, Patient_Details.Sensitivity, Patient_Details.MentalStatus,
                         Patient_Details.sleep, Patient_Details.Nutrition, Patient_Details.Vitality, Patient_Details.PhysicalStatus, Patient_Details.Nature,
                         Patient_Details.Proving, Patient_Details.RemedySource, Patient_Details.Remedytype

FROM            (Patient_Details LEFT OUTER JOIN
                         Patient_Visit ON Patient_Details.Patient_Id = Patient_Visit.Patient_Id)
WHERE        (Patient_Details.Patient_Id = @ Patient_Id)

--------------------------------------------------------------------
Query for Indesert & Update

Insert---------->

string query = " insert into UserInformation(Title,FirstName,MiddleName,LastName,Age,DateOfBirth,Status,Category,Sex)values(" + Title + "," + FirstName + "," + MiddleName + "," + LastName + "," + Age + "," + DateOfBirth + "," + Status + "," + Category + ","+Sex+")";



Update----------->

 String query = "Update from UserInformation set Title,FirstName,MiddleName,LastName,Age,Category,status,DateOfBirth,Sex='" + Title + "','" + FirstName + "','" + MiddleName + "','" + LastName + "','" + Age + "','" + Category + "','" + Status + "','" + DateOfBirth + "','" + Sex + "'  where UserId='" + UserId + "'";

-------------------------------------

______________________________________________
Code At DAL using Store Procedure:
   
public string AddNewUsersInform()
     
{
         
SqlConnection conn = new SqlConnection(Settings.ConnectionString);

 SqlCommand cmd = new SqlCommand();
         
 cmd.Connection = conn;
         
cmd.CommandText = "uspAddNewUserInformation";
         
 cmd.CommandType = CommandType.StoredProcedure;
         
 cmd.Parameters.AddWithValue("@FirstName", FirstName);
         
 cmd.Parameters.AddWithValue("@MiddleName", MiddleName);
         
 cmd.Parameters.AddWithValue("@LastName", LastName);
         
cmd.Parameters.AddWithValue("@Age", Age);
         
cmd.Parameters.AddWithValue("@DateOfBirth", DateOfBirth);
         
cmd.Parameters.AddWithValue("@Sex", Sex);
       
  cmd.Parameters.AddWithValue("@Category", Category);

         
 string result = cmd.ExecuteScalar().ToString();
       
  return result;
     

 }




Monday 11 November 2013

CODE TO CONVERT 'NOTEPAD TEXT' FILE IN HTML 'FILE' (WINDOW APPLICATION)

NOTE:- COPY  TEXT FILE'S  FOLDER  IN C DRIVE & NAMED IT AS 'DietNutrition'.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;

namespace TextToHtm
{
    class Program
    {
        static void Main(string[] args)
        {
            DirSearch(@"C:\DietNutrition");
        }
        public static void DirSearch(string sDir)
        {
            try
            {
                List<string> ttt = new List<string>();
                ttt.Add("<html><head><title>Index</title></head><body><br/>");
                foreach (string f in Directory.GetFiles(sDir))
                {
                    SearchFileAndAddToObject(f);
                    ttt.Add("<a href=" + f.Replace(".txt", ".html").Replace("DietNutrition", "DietNutritionHtm").Replace(" ", "") + ">" + f.Replace(".txt", "").Replace("DietNutrition", "DietNutritionHtm").Replace(@"C:\DietNutritionHtm\","")+"</a><br/>");
                 
                }
                ttt.Add("</body></html>");
                string f1 = @"C:\DietNutritionHtm\Index.html";
           //    File.Create(f1.Replace(" ", ""));
             File.WriteAllLines(f1.Replace(" ", ""), ttt.ToArray(), Encoding.GetEncoding("Windows-1252"));
                foreach (string d in Directory.GetDirectories(sDir))
                {

                    foreach (string f in Directory.GetFiles(d))
                    {
                        SearchFileAndAddToObject(f);
                    }

                    DirSearch(d);
                }
            }
            catch (System.Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
            Console.ReadLine();
        }
        public static void SearchFileAndAddToObject(string filename)
        {


            string[] fileByLines = File.ReadAllLines(filename, Encoding.GetEncoding("Windows-1252"));
            List<string> tt = new List<string>();

            tt.Add("<html><head><title>");
            foreach (string line in fileByLines)
            {

                string Newline;
                if(line.Contains("["))
                {
                    Newline = "<title>" + line.Substring(0, line.IndexOf("[")).Replace("Å’", "") + @"</title></head><body style=""background-image:url(qhc_body.jpg)""><table width=""100%"" cellspacing=""0"" cellpadding=""0"" border=""0""><tr><td align=""center""><img src=""logo1.png"" alt=""Logo""  /></td></tr><tr><td>";
                 
                }
                else
                    Newline = line.Replace("Å’", "<b><u style=\"Color:660066\"><hr>") + "<b> </u><br/>";
             
               tt.Add(Newline);
               Newline = Newline.Replace("•", "*").Replace("-", "*");
             
            }
            tt.Add("</td></tr></table></body></html>");
            Directory.CreateDirectory(@"C:\DietNutritionHtm");
          // File.Create(filename.Replace(".txt", ".html").Replace("DietNutrition", "DietNutritionHtm").Replace(" ", ""));
       
           File.WriteAllLines(filename.Replace(".txt", ".html").Replace("DietNutrition", "DietNutritionHtm").Replace(" ",""), tt.ToArray(), Encoding.GetEncoding("Windows-1252"));

        }
    }
}

Navigate from one page to another with value..(WINDOW APPLICATION)

Navigate from one page to another with value:-

 private void btnImage_Click(object sender, EventArgs e)
        {
            try
            {
                string adval = DiseaseLV.SelectedItems[0].SubItems[0].Text;
                Images Im = new Images();
                Im.flag = 1;
                int I;
                I = Convert.ToInt32(DiseaseLV.SelectedItems[0].SubItems[0].Text);
                Im.val = Convert.ToInt32(adval);
                Im.Show();
            }
            catch (Exception ex)
            {
             
                MessageBox.Show("Select The Index:" + Environment.NewLine + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

--------------------------------------------------
CODE FOR REPORT BY ID FROM LISTVIEW:-

private void btnCurrentReport_Click(object sender, EventArgs e)
        {
            try
               {
                string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;";
                Con = new OleDbConnection(@constr);

                SelectedDetailsId = Convert.ToInt32(DiseaseLV.SelectedItems[0].SubItems[7].Text);

                var form = new CurrentReport();
                form.Show();
               }
            catch (Exception ex)
               {
                MessageBox.Show(" Please Select The Index:" + Environment.NewLine + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
               }

               }

--------------------
public partial class DiseaseRecord : Form
    {
        public static int SelectedDetailsId;
    }
-------------------------------------------------------------
CODE FOR

CODE FOR Insert,Update,Delete & Search (Window application)

CODE FOR INSERT & UPDATE;-

 public void Disease_Load(object sender, EventArgs e)
        {
             try
             {
                 DiseaseList();
                 TreatmentList();
                 SymptomsList();


                 btnSubmit.Visible = false;
                 btnBrowse.Visible = false;
                 txtPatient_Id.Text = val.ToString();
                 txtPatientId.Text = val.ToString();
           
                if (flag == 1)
                {

                    string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;";
                    Con = new OleDbConnection(@constr);
                    Con.Open();

                    Com = new OleDbCommand();
                    Com.Connection = Con;
                    Com.CommandText = "SELECT Patient_Id,Date_of_visit,Date_of_discharge,DoctorName,Symptoms,Disease,Treatment,age,Occupation,Sensitivity,MentalStatus,Sleep,Nutrition,Vitality,PhysicalStatus,Nature,Proving,RemedySource,RemedyType FROM Patient_Details WHERE DetailsId =" + val;

                    OleDbDataReader reader = Com.ExecuteReader();

                    object[] obj = new object[256];

                    txtPatient_Id.Text = val.ToString();

                    while (reader.Read())
                    {
                        reader.GetValues(obj);
                     
                        dateTimePickerVisit.Text = obj[1].ToString();

                        dateTimePickerDischarge.Text = obj[2].ToString();

                        txtDoctorName.Text = obj[3].ToString();

                        txtSymptoms.Text = obj[4].ToString();

                        txtDisease.Text = obj[5].ToString();

                        txtTreatment.Text = obj[6].ToString();
                     
                        cmbAge.Text = obj[7].ToString();
                        cmbOccupation.Text = obj[8].ToString();
                        cmbSensitivity.Text = obj[9].ToString();
                        cmbMeritalStatus.Text = obj[10].ToString();
                        cmbSleep.Text = obj[11].ToString();
                        cmbNutrition.Text = obj[12].ToString();
                        cmbVitality.Text = obj[13].ToString();
                        cmbPhysicalStatus.Text = obj[14].ToString();
                        cmbNature.Text = obj[15].ToString();
                        cmbProving.Text = obj[16].ToString();
                        cmbRemedySource.Text = obj[17].ToString();
                        cmbRemedyType.Text = obj[18].ToString();
                    }
                    reader.Close();
                    Con.Close();
                    checkBoxImage.Enabled = false;
                      }
                   }
            catch (Exception exe)
            {
                MessageBox.Show(exe.Message);
            }
            }
   
        public void okbtn_Click(object sender, EventArgs e)
        {
     
            try
            {
                string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;";
                Con = new OleDbConnection(@constr);
                Con.Open();

                Com = new OleDbCommand();
                Com.Connection = Con;
                                                                                                 

                if (flag != 1)
                {

                    Com.CommandText = "INSERT INTO Patient_Details(Patient_Id,Date_of_visit,Date_of_discharge,Symptoms,Disease,Treatment,DoctorName,age,Occupation,Sensitivity,MentalStatus,Sleep,Nutrition,Vitality,PhysicalStatus,Nature,Proving,RemedySource,RemedyType) VALUES('" + txtPatient_Id.Text + "','" + dateTimePickerVisit.Text + "','" + dateTimePickerDischarge.Text + "','" + txtSymptoms.Text + "','" + txtDisease.Text + "','" + txtTreatment.Text + "','" + txtDoctorName.Text + "','" + cmbAge.Text + "','" + cmbOccupation.Text + "','" + cmbSensitivity.Text + "','" + cmbMeritalStatus.Text + "','" + cmbSleep.Text + "','" + cmbNutrition.Text + "','" + cmbVitality.Text + "','" + cmbPhysicalStatus.Text + "','" + cmbNature.Text + "','" + cmbProving.Text + "','" + cmbRemedySource.Text + "' ,'" + cmbRemedyType.Text + "')";

                    Com.ExecuteNonQuery();
                    Con.Close();

                    MessageBox.Show("Record Added Successfully", "PIS System");
                    DiseaseRecord D = new DiseaseRecord();
                    D.Show();
                    //checkBoxImage.Visible = true;
                     checkBoxImage.Enabled = true;
                 
                    this.Close();
                }
                else if (flag == 1)
                {
                    Com.CommandText = "UPDATE Patient_Details SET Date_of_visit ='" + dateTimePickerVisit.Text + "',Date_of_discharge = '" + dateTimePickerDischarge.Text + "',DoctorName = '" + txtDoctorName.Text + "',Symptoms = '" + txtSymptoms.Text + "',Disease = '" + txtDisease.Text + "',Treatment = '" + txtTreatment.Text + "' ,Age ='" + cmbAge.Text + "',Occupation ='" + cmbOccupation.Text + "',Sensitivity ='" + cmbSensitivity.Text + "',MentalStatus ='" + cmbMeritalStatus.Text + "',Sleep ='" + cmbSleep.Text + "',Nutrition ='" + cmbNutrition.Text + "',Vitality ='" + cmbVitality.Text + "',PhysicalStatus ='" + cmbPhysicalStatus.Text + "',Nature ='" + cmbNature.Text + "',Proving ='" + cmbProving.Text + "',RemedySource ='" + cmbRemedySource.Text + "' ,RemedyType ='" + cmbRemedyType.Text + "'  WHERE DetailsId =" + val + "";
                 


                    Com.ExecuteNonQuery();
                    Con.Close();

                    MessageBox.Show("Record Updated Successfully", "PIS System");
                    DiseaseRecord D = new DiseaseRecord();
                    D.Show();
                    this.Close();

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

---------------------
 private void updatebtn_Click(object sender, EventArgs e)
        {
            try
            {
                Disease di = new Disease();
                di.flag = 1;
                string s = "";
            //  s = DiseaseLV.SelectedItems[0].SubItems[0].Text;
                s = DiseaseLV.SelectedItems[0].SubItems[7].Text;
                di.val = Convert.ToInt32(s);
                di.Show();
                this.Close();
            }
            catch (Exception exet)
            {

                MessageBox.Show(" Please Select The Index:" + Environment.NewLine + exet.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }



CODE FOR DELETE:-

private void deletebtn_Click(object sender, EventArgs e)
        {
            try
            {
                string delval = DiseaseLV.SelectedItems[0].SubItems[7].Text;
                DialogResult r = MessageBox.Show("Are you sure you want to delete record: " + delval, "PIS System", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (r == DialogResult.Yes)
                {

                    string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;";
                    Con = new OleDbConnection(@constr);
                    Con.Open();

                    Com = new OleDbCommand();
                    Com.Connection = Con;
                    Com.CommandText = "DELETE FROM Patient_Details WHERE DetailsId = " + delval + "";
                    Com.ExecuteNonQuery();
                    Con.Close();
                                   
                    DiseaseRecord dr = new DiseaseRecord();
                    dr.Show();
                    this.Close();
                }

            }
catch (Exception ex)
            {
                MessageBox.Show(" Please Select The Index:" + Environment.NewLine + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

 CODE FOR SEARCH:-

 private void btnShowImage_Click(object sender, EventArgs e)
        {
            string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;";
            Con = new OleDbConnection(@constr);
            Con.Open();
            Com = new OleDbCommand();
            Com.Connection = Con;
        
            Com.CommandText = "SELECT Photo FROM PatientImages WHERE Patient_Id =  " + val + " ";
            OleDbDataReader reader = Com.ExecuteReader();
            if (reader.Read())
                     {
                byte[] picbyte = reader["Photo"] as byte[] ?? null;
                if (picbyte != null)
                {
                    MemoryStream mstream = new MemoryStream(picbyte);
                    pictureBoxForImage.Image = System.Drawing.Image.FromStream(mstream);
                    pictureBoxForImage.SizeMode = PictureBoxSizeMode.StretchImage;
                    {
                        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(mstream);
                    }
                }
            }




Code for Accessing Data in ListView at Page_Load,Search data from List view..(WINDOW APPLICATION)

private void DiseaseRecord_Load(object sender, EventArgs e)
        {
           try
             
            {
                string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;";
                Con = new OleDbConnection(@constr);
                Con.Open();
                Com = new OleDbCommand();
                Com.Connection = Con;
                Com.CommandText = "SELECT * FROM Patient_Details";
                OleDbDataReader reader = Com.ExecuteReader();
                object[] obj = new object[256];
                int dt = 0;
                while (reader.Read())
                {
                    reader.GetValues(obj);
                    DiseaseLV.Items.Add(obj[0].ToString());
                    DiseaseLV.Items[dt].SubItems.Add(obj[1].ToString());
                    DiseaseLV.Items[dt].SubItems.Add(obj[2].ToString());
                    DiseaseLV.Items[dt].SubItems.Add(obj[3].ToString());
                    DiseaseLV.Items[dt].SubItems.Add(obj[4].ToString());
                    DiseaseLV.Items[dt].SubItems.Add(obj[5].ToString());
                    DiseaseLV.Items[dt].SubItems.Add(obj[6].ToString());
                    DiseaseLV.Items[dt].SubItems.Add(obj[19].ToString());
                    dt++;
                }
                reader.Close();
                Con.Close();

                updatebtn.Enabled = false;
                deletebtn.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
------------------------------------------------

 private void DiseaseLV_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                btnImage.Enabled = true;
                updatebtn.Enabled = true;
                deletebtn.Enabled = true;
            }
            catch (Exception exe)
            {
                MessageBox.Show(exe.Message);
            }
        }
------------------------------------
Search Data from ListView:-

 private void Searchbtn_Click(object sender, EventArgs e)
        {
              try
            {
                bool recordFound = false;
                if (searchtxtbox.Text == "")
                {
                    MessageBox.Show("No Letter Typed", "PIS Search Engine");
                }
                else
                {
                    for (int i = 0; i <= studentvisitLV.Items.Count - 1; i++)
                    {
                        string s1 = (searchtxtbox.Text).ToLower();
                        string s2 = (studentvisitLV.Items[i].SubItems[2].Text).ToLower();

                        if (s1 == s2)
                                               
                        {
                            studentvisitLV.Items[i].BackColor = Color.Yellow;
                            recordFound = true;
                        }

                    }
                    if (!recordFound)
                    {
                        MessageBox.Show("Record Not Found", "PIS Search Engine", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


list, CheckBox,CANCEL_BUTTON,Login_Button,Back_Button, Validate TextBox..(WINDOW APPLICATION)

CODE FOR CREATING LIST:-


public partial class Disease : Form
    {
        ////List<string> Ditems = new List<string>();
        ////List<string> Sitems = new List<string>();
        ////List<string> Titems = new List<string>();

        public Disease()
        {
            InitializeComponent();


            ////Ditems.Add("Fever");
            ////Ditems.Add("Cancer");
            ////Ditems.Add("Pain");

            ////lstDisease.DataSource = Ditems;


            ////Sitems.Add("1st");
            ////Sitems.Add("2nd");
            ////Sitems.Add("3rd");

            ////lstSymptoms.DataSource = Sitems;

            ////Titems.Add("Treatment1");
            ////Titems.Add("Treatment2");
            ////Titems.Add("Treatment3");

            ////lstTreatment.DataSource = Titems;



        }
--------------------------------------------
CODE FOR ADD BUTTON  FROM LISTBOX TO TEXTBOX:-

 private void btnAddDisease_Click(object sender, EventArgs e)
        {
            txtDisease.Text += lstDisease.SelectedItem.ToString() + ",";
            lstDisease.Items.Remove(lstDisease.SelectedItem);
            ////    //txtDisease.Text += lstDisease.SelectedItem.ToString() + ",";
            ////    //lstDisease.Items.Remove(lstDisease.SelectedItem.ToString());
            ////    //lstDisease.DataSource = null;
            ////    //lstDisease.DataSource = lstDisease;

        }

------------------------------------------
CODE FOR CHECKBOX:-


 private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
         
            if (checkBoxImage.Checked)
            {
               // groupBoxImage.Show();
                btnBrowse.Visible = true;
                btnSubmit.Visible = true;
            }
            else if (!checkBoxImage.Checked )
            {
               // groupBoxImage.Hide();
                btnBrowse.Visible = false;
                btnSubmit.Visible = false;
            }


        }
--------------------------------------------------------

CODE FOR BACK BUTTON:-

private void btnBack_Click(object sender, EventArgs e)
        {
            PatientVisitationRecord sv = new PatientVisitationRecord();
            sv.Show();
            this.Close();

        }
------------------------------------------------------------
CODE FOR LOGIN BUTTON:-

 private void loginbtn_Click(object sender, EventArgs e)
        {
            try
            {
                string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;";
                Con = new OleDbConnection(@constr);
                Con.Open();

                Com = new OleDbCommand();
                Com.Connection = Con;
                Com.CommandText = "SELECT * FROM Security";

                OleDbDataReader reader = Com.ExecuteReader();
                object[] obj = new object[256];
                bool st = false;


                while (reader.Read())
                {
                    reader.GetValues(obj);
                    if ((usernametxt.Text == obj[0].ToString()) && (passwordtxt.Text == obj[1].ToString()))
                    {
                        st = true;
                        break;
                    }
                }
                reader.Close();
                Con.Close();

                if (st)
                {
                   // MessageBox.Show("Log in Successful!!!", "PIS System", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Visible = false;
                    Sectionselect f = new Sectionselect();
                    f.Show();
                }
                else
                    MessageBox.Show("INVALID!!! Try again", "PIS System", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
----------------------------------------------------------------
CODE FOR CANCEL BUTTON:-

private void cancelbtn_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dResult;
                dResult = MessageBox.Show("Do you want to Exit?", "PIS System",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (dResult.ToString() == "Yes")
                {
                    Application.Exit();

                }
                else
                    this.Visible = false;
                LogIn v = new LogIn();
                v.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

           }

--------------------------------------------------------------------------------------
Code to Validate TextBox:-

        private void okbtn_Click(object sender, EventArgs e)
        {
            try
            {
                {
                     if (textBox2.Text == "")
                    {
                        MessageBox.Show("please enter a  Surname");
                        textBox2.BackColor = Color.Pink;
                        textBox2.Focus();
                    }
                   

                    else if (textBox3.Text == "")
                        {
                            MessageBox.Show("Please enter a  First Name");
                            textBox3.BackColor = Color.Pink;
                            textBox3.Focus();
                        }
                   else if (comboBox2.Text == "")
                        {
                            MessageBox.Show("Please Select the Gender");
                            comboBox2.BackColor = Color.Pink;
                            comboBox2.Focus();
                        }

                    else if (textBox6.Text == "")
                            {
                                MessageBox.Show("Contact No. not Entered");
                                textBox6.BackColor = Color.Pink;
                                textBox6.Focus();
                            }
                        }

                    

Code To Insert Image In Database & OpenFile DailogBox (Window application)

(Code of OpenFile Dailog)

private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.InitialDirectory = "c:\\";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                textBox.Text = fd.FileName.ToString();
                pictureBox.ImageLocation = textBox.Text;
            }
            Console.ReadLine();
         
        }



----------------------------------------------------------------------
(Code For Insert Image)


private void btnSubmit_Click(object sender, EventArgs e)
        {
            byte[] picbyte = System.IO.File.ReadAllBytes(textBox.Text);
            try
            {
                string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;";
                Con = new OleDbConnection(@constr);
                Con.Open();
                Com = new OleDbCommand();
                Com.Connection = Con;
                Com.CommandText = "INSERT INTO PatientImages (Patient_Id,ImageDate,Photo,ImageName)VALUES('" + txtPatientId.Text + "','" + txtImageDate.Value.ToString("yyyy/MM/dd HH:mm:ss") + "', @Photo ,'" + txtImageName.Text + "')";
                OleDbParameter picParam = Com.Parameters.Add("@Photo", SqlDbType.Binary);
                picParam.Value = picbyte.ToArray();
                picParam.Size = picbyte.ToArray().Length;
                Com.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Con.Close();
                MessageBox.Show("Image Uploaded Successfully", "PIS System");
            }
        }
------------------------------------------------------------------
CODE FOR FETCHING IMAGES FROM DATABASE:-

private void Images_Load(object sender, EventArgs e)
            {
                FetchedImage();

            }
------------------------------


 private void FetchedImage()
        {
            lblIdImage.Text = val.ToString();
            string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;";
            Con = new OleDbConnection(@constr);
            Con.Open();
            Com = new OleDbCommand();
            Com.Connection = Con;
            OleDbDataAdapter da = new OleDbDataAdapter("SELECT Photo,ImageDate,ImageName FROM PatientImages WHERE Patient_Id =  " + val + " ", Con);
            //Initialize dataset
            ds = new DataSet();
            //Fill DataSet using query defined for DataAdapter
            da.Fill(ds);
            //da.Fill(ds, "PatientVisitation ");
            byte[] picbyte = ds.Tables[0].Rows[i]["Photo"] as byte[] ?? null;
            if (picbyte != null)
            {
                MemoryStream mstream = new MemoryStream(picbyte);
                pictureBoxForImage.Image = System.Drawing.Image.FromStream(mstream);
                pictureBoxForImage.SizeMode = PictureBoxSizeMode.StretchImage;
                {
                    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(mstream);
                }
            }
            lblImageName.Text = ds.Tables[0].Rows[i]["ImageName"].ToString();
            lblImageDate.Text = ds.Tables[0].Rows[i]["ImageDate"].ToString();
        }

  -------------------------------------------------------------------------        

CODE FOR NEXT & PREVIOUS IMAGE BUTTON:-

  private void btnNextImage_Click(object sender, EventArgs e)
        {
                if (i < ds.Tables[0].Rows.Count - 1)
            {
                i++;

                byte[] picbyte = ds.Tables[0].Rows[i]["Photo"] as byte[] ?? null;
                if (picbyte != null)
                {
                    MemoryStream mstream = new MemoryStream(picbyte);
                    pictureBoxForImage.Image = System.Drawing.Image.FromStream(mstream);
                    pictureBoxForImage.SizeMode = PictureBoxSizeMode.StretchImage;
                    {
                        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(mstream);
                    }
                }
                lblImageName.Text = ds.Tables[0].Rows[i]["ImageName"].ToString();
                lblImageDate.Text = ds.Tables[0].Rows[i]["ImageDate"].ToString();
            }
            else
            {
                MessageBox.Show("Next Image not available");
            }
         
           }


        private void btnPreviewImage_Click(object sender, EventArgs e)
        {
         
            if (i == ds.Tables[0].Rows.Count - 1 || i != 0)
            {
                i--;
                byte[] picbyte = ds.Tables[0].Rows[i]["Photo"] as byte[] ?? null;
                if (picbyte != null)
                {
                    MemoryStream mstream = new MemoryStream(picbyte);
                    pictureBoxForImage.Image = System.Drawing.Image.FromStream(mstream);
                    pictureBoxForImage.SizeMode = PictureBoxSizeMode.StretchImage;
                    {
                        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(mstream);
                    }
                }
                lblImageName.Text = ds.Tables[0].Rows[i]["ImageName"].ToString();
                lblImageDate.Text = ds.Tables[0].Rows[i]["ImageDate"].ToString();
            }
            else
            {
                MessageBox.Show("Previous Image not available");
            }
         

        }

Code for Accessing data from Database To ListBox, Validate TextBox for Phone no. (Window application)

public void Disease_Load(object sender, EventArgs e)
        {
          DiseaseList();
           }
-----------------------------------
private void DiseaseList()
        {
            string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\PIS(ACU).mdb;";
            Con = new OleDbConnection(@constr);
            Con.Open();
            Com = new OleDbCommand();
            Com.Connection = Con;

            Com.CommandText = "SELECT DiseaseName FROM Disease";
            OleDbDataReader da = Com.ExecuteReader();
            object[] obj = new object[256];
            while (da.Read())
            {
                da.GetValues(obj);
                lstDisease.Items.Add((string)da["DiseaseName"]);
             }
            da.Close();
            Con.Close();
        }
---------------------------------------
 private void txtContactNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
                && !char.IsDigit(e.KeyChar)
                && e.KeyChar != '.')
            {
                e.Handled = true;
            }

            if (e.KeyChar == '.'
             && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }