Sunday 12 April 2015

TextBox Validtion in Windows Applictaion in C#

windows application 
+++++++++++++++++++++++++++++++ 

textbox validation 
+++++++++++++++++++++++++++++++ 


mail id validation 
||||||||||||||||||||||||||| 

private void textBox1_Validating(object sender, 
System.ComponentModel.CancelEventArgs e) 

string errorMsg; 
if(!ValidEmailAddress(textBox1.Text, out errorMsg)) 

// Cancel the event and select the text to be corrected by the user. 
e.Cancel = true; 
textBox1.Select(0, textBox1.Text.Length); 

// Set the ErrorProvider error with the text to display. 
this.errorProvider1.SetError(textBox1, errorMsg); 



private void textBox1_Validated(object sender, System.EventArgs e) 

// If all conditions have been met, clear the ErrorProvider of errors. 
errorProvider1.SetError(textBox1, ""); 

public bool ValidEmailAddress(string emailAddress, out string errorMessage) 

// Confirm that the e-mail address string is not empty. 
if(emailAddress.Length == 0) 

errorMessage = "e-mail address is required."; 
return false; 


// Confirm that there is an "@" and a "." in the e-mail address, and in the correct order. 
if(emailAddress.IndexOf("@") > -1) 

if(emailAddress.IndexOf(".", emailAddress.IndexOf("@") ) > emailAddress.IndexOf("@") ) 

errorMessage = ""; 
return true; 



errorMessage = "e-mail address must be valid e-mail address format.\n" + 
"For example 'someone@example.com' "; 
return false; 




++++++++++++++++++++++++++++++++++++++++++++++++++ 


textbox validation accepts number only 
++++++++++++++++++++++++++++++++++++++++ 



private void textBox3_Validating(object sender, CancelEventArgs e) 

try 

int numberEntered = int.Parse(textBox3.Text); 
if (numberEntered < 1 || numberEntered > 10) 

e.Cancel = true; 
MessageBox.Show("You have to enter a number between 1 and 10"); 


catch (FormatException) 

e.Cancel = true; 
MessageBox.Show("You need to enter an integer"); 





++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 


only numbers and a dot 
+++++++++++++++++++++++++++++++++++ 


private void textBox2_TextChanged(object sender, EventArgs e) 


if (!(string.IsNullOrEmpty(textBox2.Text))) 


char[] chars = textBox2.Text.ToCharArray(); 
for (int i = 0; i < textBox2.Text.Length; i++) 

int code; 
code = Convert.ToInt16(chars [i] ); 
if (!((!(code > 58 || code < 48)) || (code == 68) || (code == 78) || (code == 35) || (code == 46))) 

textBox2.Text = textBox2.Text.Remove(i, 1); 
textBox2.SelectionStart = textBox2.Text.Length; 




++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 

e-mail validation 

++++++++++++++++++++++++++++ 


private void textBox1_Validating(object sender, CancelEventArgs e) 

System.Text.RegularExpressions.Regex rEMail = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"); 
if (textBox1.Text.Length > 0) 

if (!rEMail.IsMatch(textBox1.Text)) 

MessageBox.Show("E-Mail expected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
textBox1.SelectAll(); 
e.Cancel = true; 




+++++++++++++++++++++++++++++++++++++++ 


TEXTBOX ONLY ACCEPTS CHARACTERS 
++++++++++++++++++++++++++++++++++ 

private void textBox4_KeyPress(object sender, KeyPressEventArgs e) 

if ((e.KeyChar >= 65 && e.KeyChar <= 90) || (e.KeyChar >= 97 && e.KeyChar <= 122) || e.KeyChar == 32 || e.KeyChar == 8) 

e.Handled = false; 

else 

MessageBox.Show("Invalid Input"); 
e.Handled = true; 


+++++++++++++++++++++++++++++++++++++++

Saturday 11 April 2015

Windows Application In C# with Sql Server (Save Update and Delete)


**************************************************************
Sql Procedure

**********************************************************


Create PROCEDURE [DBO].[USPPHONEDIRECTORY]
(
@PHONEID   INT            =NULL ,
@NAME      VARCHAR(50)    =NULL,
@COUNTRYID INT            = NULL,
@STATEID   INT            =NULL,
@EMAILID   VARCHAR(50)    =NULL,
@PHONENO   VARCHAR(50)    =NULL,
@CAST      DECIMAL(18,0)  =NULL,
@MODEL     VARCHAR(50)    =NULL,
@FLAG      INT

)
AS
BEGIN
IF @FLAG =0
BEGIN
 SELECT PHONEDIRECTORY.[PHONEID]
,PHONEDIRECTORY.[NAME]
,PHONEDIRECTORY.COUNTRYID
       ,[COUNTRYMASTER].COUNTRYNAME
,PHONEDIRECTORY.STATEID
,[STATEMASTER].STATENAME
,PHONEDIRECTORY.[EMAILID]
,PHONEDIRECTORY.[PHONE]
,PHONEDIRECTORY.[CAST]
,PHONEDIRECTORY.[MODEL]FROM  DBO.PHONEDIRECTORY
    LEFT OUTER JOIN [STATEMASTER] ON PHONEDIRECTORY.STATEID=[STATEMASTER].STATEID
    LEFT OUTER JOIN [COUNTRYMASTER] ON PHONEDIRECTORY.COUNTRYID=[COUNTRYMASTER].COUNTRYID
END

IF @FLAG =1
 BEGIN
                     SELECT  COUNTRYID,  COUNTRYNAME FROM [COUNTRYMASTER]
   
 END

 IF @FLAG =2
 BEGIN
                     SELECT  STATEID,  STATENAME FROM [STATEMASTER]  WHERE COUNTRYID=@COUNTRYID
   
 END
IF @FLAG =3
 BEGIN
DECLARE @RECID BIGINT
 IF((SELECT COUNT(*) FROM DBO.PHONEDIRECTORY WHERE NAME=@NAME)>0)
BEGIN
RETURN -1
END
BEGIN
INSERT INTO PHONEDIRECTORY (NAME,COUNTRYID ,STATEID,EMAILID,PHONE,CAST ,MODEL)
VALUES(@NAME,@COUNTRYID ,@STATEID,@EMAILID,@PHONENO,@CAST,@MODEL)
IF @@ERROR>0        
 BEGIN        
RETURN 0        
 END        
 ELSE        
 BEGIN        
SELECT @RECID=IDENT_CURRENT('PHONEDIRECTORY')        
RETURN @RECID        
 END
 END
 END

IF @FLAG =4
 BEGIN
  --IF((SELECT COUNT(*) FROM DBO.PHONEDIRECTORY WHERE NAME=@NAME AND PHONEID<>@PHONEID)=1)
-- BEGIN
-- RETURN -1
-- END
--    ELSE
 
--BEGIN  

UPDATE   PHONEDIRECTORY
SET NAME=@NAME,
COUNTRYID=@COUNTRYID ,
STATEID=@STATEID,
EMAILID=@EMAILID,
PHONE=@PHONENO,
CAST=@CAST ,
MODEL=@MODEL
WHERE [PHONEID]=@PHONEID
  IF @@ERROR<>0 OR @@ROWCOUNT>1      
BEGIN      
RETURN 0      
END      
ELSE      
 BEGIN      
  RETURN 1      
 END
  --END
 END
IF @FLAG =5
 BEGIN
DELETE FROM PHONEDIRECTORY
WHERE [PHONEID]=@PHONEID
IF @@ERROR<>0 OR @@ROWCOUNT>1      
BEGIN      
RETURN 0      
END      
ELSE      
 BEGIN      
  RETURN 1      
 END

 END

 END


***********************************************
Web Config

******************************************************

<appSettings>
<add key="RamTech" value="Data Source=HP-HP\SECSQL; Initial Catalog=Test;Integrated Security =True"/>
</appSettings>



*****************************************************
Coding (Opration Page)
****************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Transactions;

namespace WindowsPhoneDirectory
{
    public partial class frmPhoneDirectory : Form
    {
        string cnnstr = System.Configuration.ConfigurationSettings.AppSettings["Ramtech"].ToString();
        SqlConnection CNN = new SqlConnection();
        public int PhoneId = 0;
        public frmPhoneDirectory()
        {
            InitializeComponent();
            CNN.ConnectionString = cnnstr;
         
           
        }
     
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (fnValidation() == true)
                {
                    try
                    {
                        long intsave = fnSaveRecords();
                        if (intsave > 0)
                        {
                           
                            fnBindData();
                            fnClear();
                            txtName.Enabled = true;
                            txtModel.Enabled = true;
                            txtCast.Enabled = true;
                            txtPhone.Enabled = true;
                            txtEmail.Enabled = true;
                            cmbCountry.Enabled = true;
                            cmbState.Enabled = true;
                            btnUpdate.Enabled = false;
                            btnSave.Enabled = true;
                            btndelete.Enabled = false;
                            PhoneId = 0;
                            MessageBox.Show("Save Record Succesfully !", "Phone Directory");
                        }
                        else if (intsave == -1)
                        {

                            MessageBox.Show("Duplicate Records Can Not Saved  !", "Phone Directory");
                        }
                        else
                        {
                            MessageBox.Show("Error in Saveing process Can Not Saved  !", "Phone Directory");
                        }
                     
                    }
                    catch (Exception Ex)
                    {
                        MessageBox.Show("Invalid Oparation ?", "Phone Directory");
                    }

                }

            }
            catch (Exception Ex)
            {
                MessageBox.Show("Invalid Oparation ?", "Phone Directory");
            }
        }

        private void btndelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (PhoneId > 0)
                {
                    long intdel = fnDeleteRecords();
                    if (intdel > 0)
                    {

                        fnBindData();
                        fnEnableControl();
                        fnClear();
                        MessageBox.Show("Delete Record Succesfully !", "Phone Directory");

                    }


                }
                else
                {

                    //foreach (DataGridViewRow row in grvList.Rows)
                    //{
                    //    bool isSelected = Convert.ToBoolean(row.Cells["checkBoxColumn"].Value);
                    //    if (isSelected)
                    //    {
                    //        PhoneId = Convert.ToInt32(row.Cells["PhoneId"].Value.ToString());
                    //    }
                    //}
                }


            }
            catch(Exception Ex)
            {

            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                fnEnableControl();
                fnClear();
            }
            catch (Exception Ex)
            {
                MessageBox.Show(" Error In Cancel  ?", "Phone Directory");
            }
        }

        public long fnSaveRecords()
        {
            SqlTransaction SQLT = null;
            int recId = 0;
            bool Berror = false;
            SqlCommand CMD = new SqlCommand();
            try
            {
                try
                {
                    if (CNN.State == ConnectionState.Closed)
                        CNN.Open();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                }
                SQLT = CNN.BeginTransaction();
                CMD.Transaction = SQLT;
                CMD.Connection = CNN;
                CMD.CommandType = CommandType.StoredProcedure;
                CMD.CommandText = "uspPhoneDirectory";
                CMD.Parameters.Clear();
                CMD.Parameters.AddWithValue("@name", txtName.Text);
                CMD.Parameters.AddWithValue("@CountryID", cmbCountry.SelectedValue);
                CMD.Parameters.AddWithValue("@StateID", cmbState.SelectedValue);
                CMD.Parameters.AddWithValue("@EmailID", txtEmail.Text);
                CMD.Parameters.AddWithValue("@phoneNo", txtPhone.Text);
                CMD.Parameters.AddWithValue("@Cast", txtCast.Text);
                CMD.Parameters.AddWithValue("@Model", txtModel.Text);
                CMD.Parameters.AddWithValue("@Flag", 3);
                SqlParameter SQLPar = new SqlParameter();
                SQLPar = CMD.Parameters.Add("RETURN_VALUE", SqlDbType.BigInt);
                SQLPar.Direction = ParameterDirection.ReturnValue;
                recId = CMD.ExecuteNonQuery();
                if (recId == 0)
                {
                    Berror = true;

                }

                if (Berror == true)
                {
                    CMD.Transaction.Rollback();
                    return 0;
                }
                else
                {
                    CMD.Transaction.Commit();

                }

            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (CNN.State != ConnectionState.Closed)
                    CNN.Close();
            }
            return recId;

        }
        public long fnUpdateRecords()
        {
            SqlTransaction SQLT = null;
            int recId = 0;
            bool Berror = false;
            SqlCommand CMD = new SqlCommand();
            try
            {
                try
                {
                    if (CNN.State == ConnectionState.Closed)
                        CNN.Open();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                }
                SQLT = CNN.BeginTransaction();
                CMD.Transaction = SQLT;
                CMD.Connection = CNN;
                CMD.CommandType = CommandType.StoredProcedure;
                CMD.CommandText = "uspPhoneDirectory";
                CMD.Parameters.Clear();
                CMD.Parameters.AddWithValue("@PhoneID", PhoneId);
                CMD.Parameters.AddWithValue("@name", txtName.Text);
                CMD.Parameters.AddWithValue("@CountryID", cmbCountry.SelectedValue);
                CMD.Parameters.AddWithValue("@StateID", cmbState.SelectedValue);
                CMD.Parameters.AddWithValue("@EmailID", txtEmail.Text);
                CMD.Parameters.AddWithValue("@phoneNo", txtPhone.Text);
                CMD.Parameters.AddWithValue("@Cast", txtCast.Text);
                CMD.Parameters.AddWithValue("@Model", txtModel.Text);
                CMD.Parameters.AddWithValue("@Flag", 4);
                SqlParameter SQLPar = new SqlParameter();
                SQLPar = CMD.Parameters.Add("RETURN_VALUE", SqlDbType.BigInt);
                SQLPar.Direction = ParameterDirection.ReturnValue;
                recId = CMD.ExecuteNonQuery();
                if (recId == 0)
                {
                    Berror = true;

                }

                if (Berror == true)
                {
                    CMD.Transaction.Rollback();
                    return 0;
                }
                else
                {
                    CMD.Transaction.Commit();

                }

            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (CNN.State != ConnectionState.Closed)
                    CNN.Close();
            }
            return recId;

        }
        public long fnDeleteRecords()
        {
            SqlTransaction SQLT = null;
            int recId = 0;
            bool Berror = false;
            SqlCommand CMD = new SqlCommand();
            try
            {
                try
                {
                    if (CNN.State == ConnectionState.Closed)
                        CNN.Open();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                }
                SQLT = CNN.BeginTransaction();
                CMD.Transaction = SQLT;
                CMD.Connection = CNN;
                CMD.CommandType = CommandType.StoredProcedure;
                CMD.CommandText = "uspPhoneDirectory";
                CMD.Parameters.Clear();
                CMD.Parameters.AddWithValue("@PhoneID", PhoneId);
                CMD.Parameters.AddWithValue("@Flag", 5);
                SqlParameter SQLPar = new SqlParameter();
                SQLPar = CMD.Parameters.Add("RETURN_VALUE", SqlDbType.BigInt);
                SQLPar.Direction = ParameterDirection.ReturnValue;
                recId = CMD.ExecuteNonQuery();
                if (recId == 0)
                {
                    Berror = true;

                }

                if (Berror == true)
                {
                    CMD.Transaction.Rollback();
                    return 0;
                }
                else
                {
                    CMD.Transaction.Commit();

                }

            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (CNN.State != ConnectionState.Closed)
                    CNN.Close();
            }
            return recId;

        }

        public Boolean fnValidation()
        {
            if (txtName.Text == "")
            {
                MessageBox.Show("Name Could not be Blank ?", "Phone Directory");
                return false;
            }
            if (cmbCountry.SelectedText == "Select Value ")
            {
                MessageBox.Show("Select Country Name?", "Phone Directory");
                return false;
            }
            if (cmbState.SelectedText == "Select Value")
            {
                MessageBox.Show("Select State Name?", "Phone Directory");
                return false;
            }

            if (txtEmail.Text == "")
            {
                MessageBox.Show("Email Could not be Blank ?", "Phone Directory");
                return false;
            }

            if (txtPhone.Text == "")
            {
                MessageBox.Show("Phone Could not be Blank ?", "Phone Directory");
                return false;
            }

            if (txtCast.Text == "")
            {
                MessageBox.Show("Cast Could not be Blank ?", "Phone Directory");
                return false;
            }

            if (txtModel.Text == "")
            {
                MessageBox.Show("Model Could not be Blank ?", "Phone Directory");
                return false;
            }
            return true;
        }

        public void fnClear()
        {
            txtName.Text = "";
            txtModel.Text = "";
            txtCast.Text = "";
            txtPhone.Text = "";
            txtEmail.Text = "";
            cmbCountry.SelectedValue = 0;
            cmbState.SelectedValue = 0;
            PhoneId = 0;
        }


        public DataSet fnGetCountry()
        {
            DataSet dsGlobal = new DataSet();
            try
            {
                SqlDataAdapter adapGlobal = new SqlDataAdapter();
                SqlCommand CMD = new SqlCommand();
                try
                {
                    if (CNN.State == ConnectionState.Closed)
                        CNN.Open();
                }
                catch (Exception ex)
                {
                    CNN.Close();

                }
                if (CNN.State == ConnectionState.Closed)
                    CNN.Open();
                CMD.Connection = CNN;
                CMD.CommandType = CommandType.StoredProcedure;
                CMD.Parameters.Clear();
                CMD.CommandText = "uspPhoneDirectory";
                CMD.Parameters.AddWithValue("@Flag", 1);
                adapGlobal.SelectCommand = CMD;
                adapGlobal.Fill(dsGlobal);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                CNN.Close();

            }

            return dsGlobal;


        }
   

        public DataSet fnGetState(long CountryID)
        {
            DataSet dsGlobal = new DataSet();
            try
            {
                SqlDataAdapter adapGlobal = new SqlDataAdapter();
                SqlCommand CMD = new SqlCommand();
                try
                {
                    if (CNN.State == ConnectionState.Closed)
                        CNN.Open();
                }
                catch (Exception ex)
                {
                    CNN.Close();

                }
                if (CNN.State == ConnectionState.Closed)
                    CNN.Open();
                CMD.Connection = CNN;
                CMD.CommandType = CommandType.StoredProcedure;
                CMD.Parameters.Clear();
                CMD.CommandText = "uspPhoneDirectory";
                CMD.Parameters.AddWithValue("@CountryID", CountryID);
                CMD.Parameters.AddWithValue("@Flag", 2);
                adapGlobal.SelectCommand = CMD;
                adapGlobal.Fill(dsGlobal);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                CNN.Close();

            }

            return dsGlobal;


        }

        private void frmPhoneDirectory_Load(object sender, EventArgs e)
            {
            try
            {
                PhoneId = 0;
                cmbState.Items.Add("-Select");
                cmbCountry.Items.Add("-Select");
                fnGridColumnCreate();
             
                fnBindData();
                DataSet dscountry = new DataSet();
                dscountry = fnGetCountry();
                //DataRow dr = new DataRow();
                //dr = dscountry.Tables[0].NewRow();
                //dr[0] = "-1";
                //dr[1] = "-Select-";
                //dscountry.Tables[0].Rows.InsertAt(dr, 0);
                if (dscountry.Tables.Count > 0)
                {
                    if (dscountry.Tables[0].Rows.Count > 0)
                    {
                        cmbCountry.DataSource = dscountry.Tables[0];
                        cmbCountry.ValueMember = "CountryID";
                        cmbCountry.DisplayMember = "CountryName";
                    }
                }
                fnEnableControl();
                fnClear();
            }
            catch (Exception Ex)
            {

                MessageBox.Show(" Error In Country Population  ?", "Phone Directory");

            }
        }

        private void cmbCountry_SelectedIndexChanged(object sender, EventArgs e)
        {

             try
             {
                 long countryId = 0;
                 countryId = cmbCountry.SelectedIndex;
                 DataSet dsState = new DataSet();


                 dsState = fnGetState(countryId);
                 if (dsState.Tables.Count > 0)
                 {
                     if (dsState.Tables[0].Rows.Count > 0)
                     {
                         cmbState.DataSource = dsState.Tables[0];
                         cmbState.ValueMember = "StateId";
                         cmbState.DisplayMember = "StateName";
                     }
                 }


             }
             catch (Exception Ex)
             {
                 MessageBox.Show(" Error In Country  Selection Change  ?", "Phone Directory");
             }

        }

        private void btnShowlist_Click(object sender, EventArgs e)
        {
            try
            {
                frmShowlist frmslist = new frmShowlist();
                frmslist.ShowDialog();
            }
            catch (Exception Ex)
            {

                MessageBox.Show(" Error In Show in list ?", "Phone Directory");
            }
        }

        private void fnGridColumnCreate()
        {
            //Set AutoGenerateColumns False
            grvList.AutoGenerateColumns = false;
            //Set Columns Count
            grvList.ColumnCount = 10;

            //Add a CheckBox Column to the DataGridView at the first position.
         

            //Add Columns
            grvList.Columns[0].Name = "PhoneID";
            grvList.Columns[0].HeaderText = "Phone ID";
            grvList.Columns[0].DataPropertyName = "PhoneID";
            grvList.Columns[0].Visible = false;
            grvList.Columns[0].ReadOnly = true;

            grvList.Columns[1].HeaderText = "Name";
            grvList.Columns[1].Name = "Name";
            grvList.Columns[1].DataPropertyName = "Name";
            grvList.Columns[1].ReadOnly = true;

            grvList.Columns[2].Name = "CountryID";
            grvList.Columns[2].HeaderText = "CountryID";
            grvList.Columns[2].DataPropertyName = "CountryID";
            grvList.Columns[2].Visible = false;


            grvList.Columns[3].Name = "CountryName";
            grvList.Columns[3].HeaderText = "Country";
            grvList.Columns[3].DataPropertyName = "CountryName";
            grvList.Columns[3].ReadOnly = true;

           

            grvList.Columns[4].Name = "StateID";
            grvList.Columns[4].HeaderText = "StateID ";
            grvList.Columns[4].DataPropertyName = "StateID";
            grvList.Columns[4].Visible = false;

            grvList.Columns[5].Name = "StateName";
            grvList.Columns[5].HeaderText = "State ";
            grvList.Columns[5].DataPropertyName = "StateName";
            grvList.Columns[5].ReadOnly = true;

            grvList.Columns[6].Name = "EmailID";
            grvList.Columns[6].HeaderText = "EmailID ";
            grvList.Columns[6].DataPropertyName = "EmailID";
            grvList.Columns[6].ReadOnly = true;


            grvList.Columns[7].Name = "Phone";
            grvList.Columns[7].HeaderText = "Phone ";
            grvList.Columns[7].DataPropertyName = "Phone";
            grvList.Columns[7].ReadOnly = true;

            grvList.Columns[8].Name = "Cast";
            grvList.Columns[8].HeaderText = "Cast ";
            grvList.Columns[8].DataPropertyName = "Cast";
            grvList.Columns[8].ReadOnly = true;

            grvList.Columns[9].Name = "Model";
            grvList.Columns[9].HeaderText = "Model ";
            grvList.Columns[9].DataPropertyName = "Model";
            grvList.Columns[9].ReadOnly = true;

            DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
            checkBoxColumn.HeaderText = "";
            checkBoxColumn.Width = 30;
            checkBoxColumn.Name = "checkBoxColumn";
            grvList.Columns.Insert(10, checkBoxColumn);


        }

        public DataSet fnGetRecords()
        {

            DataSet dsGlobal = new DataSet();
            try
            {
                SqlDataAdapter adapGlobal = new SqlDataAdapter();
                SqlCommand CMD = new SqlCommand();
                try
                {
                    if (CNN.State == ConnectionState.Closed)
                        CNN.Open();
                }
                catch (Exception ex)
                {
                    CNN.Close();

                }
                if (CNN.State == ConnectionState.Closed)
                    CNN.Open();
                CMD.Connection = CNN;
                CMD.CommandType = CommandType.StoredProcedure;
                CMD.Parameters.Clear();
                CMD.CommandText = "uspPhoneDirectory";
                CMD.Parameters.AddWithValue("@Flag", 0);
                adapGlobal.SelectCommand = CMD;
                adapGlobal.Fill(dsGlobal);
            }
            catch (Exception ex)
            {
                MessageBox.Show(" Error In Getting  Grid Records  ?", "Phone Directory");
            }
            finally
            {
                CNN.Close();

            }

            return dsGlobal;

        }

        public void fnBindData()
        {
            try
            {
                DataSet DS = new DataSet();
                DS = fnGetRecords();
                if (DS.Tables.Count > 0)
                {
                    if (DS.Tables[0].Rows.Count > 0)
                    {
                        grvList.DataSource = DS.Tables[0];
                    }
                }

            }
            catch (Exception eX)
            {
                MessageBox.Show(" Error In Binding Grid  ?", "Phone Directory");
            }

        }

       
        public void fnEnableControl()
        {
            try
            {
                txtName.Enabled = false;
                txtModel.Enabled = false;
                txtCast.Enabled = false;
                txtPhone.Enabled = false;
                txtEmail.Enabled = false;
                cmbCountry.Enabled = false;
                cmbState.Enabled = false;
                btnUpdate.Enabled = false;
                btnSave.Enabled = false;
                btndelete.Enabled = false;

            }
            catch (Exception Ex)
            {
                MessageBox.Show(" Error In Disable Control  ?", "Phone Directory");
            }

        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (fnValidation() == true)
                {
                    try
                    {
                        if(PhoneId>0)
                        {
                            long intUpdate = fnUpdateRecords();
                            if (intUpdate > 0)
                            {
                                fnBindData();
                             
                                MessageBox.Show("Update Record Succesfully !", "Phone Directory");
                            }
                            //else if (intUpdate == -1)
                            //{

                            //    MessageBox.Show("Duplicate Records Can Not Update  !", "Phone Directory");
                            //}
                            //else
                            //{
                            //    MessageBox.Show("Error in Updated process Can Not Update  !", "Phone Directory");
                            //}


                        }
                     
                    }
                    catch (Exception Ex)
                    {
                        MessageBox.Show("Invalid Oparation Upadte ?", "Phone Directory");
                    }

                }

            }
            catch (Exception Ex)
            {
                MessageBox.Show("Invalid Oparation ?", "Phone Directory");
            }

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                txtName.Enabled = true;
                txtModel.Enabled = true;
                txtCast.Enabled = true;
                txtPhone.Enabled = true;
                txtEmail.Enabled = true;
                cmbCountry.Enabled = true;
                cmbState.Enabled = true;
                btnUpdate.Enabled = false;
                btnSave.Enabled = true;
                btndelete.Enabled = false;
                fnClear();

            }
            catch (Exception Ex)
            {
                MessageBox.Show(" Error In Disable Control  ?", "Phone Directory");
            }


        }
        private void grvList_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex > -1 && e.ColumnIndex > -1)
                {
                    PhoneId = 0;
                    txtName.Enabled = true;
                    txtModel.Enabled = true;
                    txtCast.Enabled = true;
                    txtPhone.Enabled = true;
                    txtEmail.Enabled = true;
                    cmbCountry.Enabled = true;
                    cmbState.Enabled = true;
                    btnUpdate.Enabled = true;
                    btnSave.Enabled = false;
                    btndelete.Enabled = true;
                    PhoneId = Convert.ToInt32(grvList.Rows[e.RowIndex].Cells[0].Value.ToString());
                    txtName.Text = grvList.Rows[e.RowIndex].Cells[1].Value.ToString();
                    cmbCountry.SelectedValue = Convert.ToInt32(grvList.Rows[e.RowIndex].Cells[2].Value.ToString());
                    cmbState.SelectedValue = Convert.ToInt32(grvList.Rows[e.RowIndex].Cells[4].Value.ToString());
                    txtPhone.Text = grvList.Rows[e.RowIndex].Cells[6].Value.ToString();
                    txtEmail.Text = grvList.Rows[e.RowIndex].Cells[7].Value.ToString();
                    txtCast.Text = grvList.Rows[e.RowIndex].Cells[8].Value.ToString();
                    txtModel.Text = grvList.Rows[e.RowIndex].Cells[9].Value.ToString();




                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(" Error In Cell Double Click  ?", "Phone Directory");

            }
        }

        private void txtCast_KeyPress(object sender, KeyPressEventArgs e)
        {
            // Only Allow Number

            if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
                e.Handled = true;

        }

        private void txtModel_KeyPress(object sender, KeyPressEventArgs e)
        {
            // only Allow Charecter
            //if (Char.IsControl(e.KeyChar) != true && Char.IsNumber(e.KeyChar) == true)
            //{
            //    e.Handled = true;
            //}

            if ((e.KeyChar >= 65 && e.KeyChar <= 90) || (e.KeyChar >= 97 && e.KeyChar <= 122) || e.KeyChar == 32 || e.KeyChar == 8 || e.KeyChar==43)
            {
                e.Handled = false;
            }
            else
            {
                //MessageBox.Show("Invalid Input");
                e.Handled = true;
            }
        }

        private void txtEmail_Validating(object sender, CancelEventArgs e)
        {
            System.Text.RegularExpressions.Regex rEMail = new
            System.Text.RegularExpressions.Regex(@"^[a-zA-Z][\w\.-]{2,28}[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
            if (txtEmail.Text.Length > 0)
            {
                if (!rEMail.IsMatch(txtEmail.Text))
                {
                    MessageBox.Show("E-Mail expected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtEmail.SelectAll();
                    e.Cancel = true;
                }

            }


        }  
     
    }
}



*************************************************************

Show list Page

******************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsPhoneDirectory
{


    public partial class frmShowlist : Form
    {  
        string cnnstr = System.Configuration.ConfigurationSettings.AppSettings["Ramtech"].ToString();
        SqlConnection CNN = new SqlConnection(); 
        
        public frmShowlist()
        {
            InitializeComponent();
            CNN.ConnectionString = cnnstr;
            fnGridColumnCreate();
            
        }

        private void frmShowlist_Load(object sender, EventArgs e)
        {
            try
            {
                fnBindData();
            }
            catch (Exception Ex)
            {
                MessageBox.Show(" Error In Binding Grid  ?", "Phone Directory");
            }

        }

        private void fnGridColumnCreate()
        {
            //Set AutoGenerateColumns False
            frvShowList.AutoGenerateColumns = false;
            //Set Columns Count
            frvShowList.ColumnCount = 8;
            //Add Columns
            frvShowList.Columns[0].Name = "PhoneID";
            frvShowList.Columns[0].HeaderText = "Phone ID";
            frvShowList.Columns[0].DataPropertyName = "PhoneID";
            frvShowList.Columns[0].Visible = false;
            frvShowList.Columns[0].ReadOnly = true;

            frvShowList.Columns[1].HeaderText = "Name";
            frvShowList.Columns[1].Name = "Name";
            frvShowList.Columns[1].DataPropertyName = "Name";
            frvShowList.Columns[1].ReadOnly = true;

            frvShowList.Columns[2].Name = "CountryName";
            frvShowList.Columns[2].HeaderText = "Country";
            frvShowList.Columns[2].DataPropertyName = "CountryName";
            frvShowList.Columns[2].ReadOnly = true;

            frvShowList.Columns[3].Name = "StateName";
            frvShowList.Columns[3].HeaderText = "State ";
            frvShowList.Columns[3].DataPropertyName = "StateName";
            frvShowList.Columns[3].ReadOnly = true;

            frvShowList.Columns[4].Name = "EmailID";
            frvShowList.Columns[4].HeaderText = "EmailID ";
            frvShowList.Columns[4].DataPropertyName = "EmailID";
            frvShowList.Columns[4].ReadOnly = true;


            frvShowList.Columns[5].Name = "Phone";
            frvShowList.Columns[5].HeaderText = "Phone ";
            frvShowList.Columns[5].DataPropertyName = "Phone";
            frvShowList.Columns[5].ReadOnly = true;

            frvShowList.Columns[6].Name = "Cast";
            frvShowList.Columns[6].HeaderText = "Cast ";
            frvShowList.Columns[6].DataPropertyName = "Cast";
            frvShowList.Columns[6].ReadOnly = true;

            frvShowList.Columns[7].Name = "Model";
            frvShowList.Columns[7].HeaderText = "Model ";
            frvShowList.Columns[7].DataPropertyName = "Model";
            frvShowList.Columns[7].ReadOnly = true;



        }

        public DataSet fnGetRecords()
        {

            DataSet dsGlobal = new DataSet();
            try
            {
                SqlDataAdapter adapGlobal = new SqlDataAdapter();
                SqlCommand CMD = new SqlCommand();
                try
                {
                    if (CNN.State == ConnectionState.Closed)
                        CNN.Open();
                }
                catch (Exception ex)
                {
                    CNN.Close();

                }
                if (CNN.State == ConnectionState.Closed)
                    CNN.Open();
                CMD.Connection = CNN;
                CMD.CommandType = CommandType.StoredProcedure;
                CMD.Parameters.Clear();
                CMD.CommandText = "uspPhoneDirectory";
                CMD.Parameters.AddWithValue("@Flag", 0);
                adapGlobal.SelectCommand = CMD;
                adapGlobal.Fill(dsGlobal);
            }
            catch (Exception ex)
            {
                MessageBox.Show(" Error In Getting  Grid Records  ?", "Phone Directory");
            }
            finally
            {
                CNN.Close();

            }

            return dsGlobal;

        }

        public void fnBindData()
        {
            try
            {
                DataSet DS = new DataSet();
                DS = fnGetRecords();
                if (DS.Tables.Count > 0)
                {
                    if (DS.Tables[0].Rows.Count > 0)
                    {
                        frvShowList.DataSource = DS.Tables[0];
                        
                    }

                }

            }
            catch (Exception eX)
            {
                MessageBox.Show(" Error In Binding Grid  ?", "Phone Directory");
            }

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            try
            {
                this.Close();
            }
            catch (Exception Ex)
            {
                MessageBox.Show(" Error In Closing List  ?", "Phone Directory");
            }
        }

        private void frvShowList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex > -1 && e.ColumnIndex > -1)
                {

                    int PhoneId = Convert.ToInt32(frvShowList.Rows[e.RowIndex].Cells[0].Value.ToString());
                   
                   
                }

            }
            catch (Exception Ex)
            {
            }

        }
        
          

    }
}