Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Fully Object Oriented AddressBook with Database in C# .NET Created By => Hiten Patel

0.00/5 (No votes)
15 May 2002 1  
AddressBook In C# with Database

Introduction

Hi MySelf Hiten Patel

This is my second project i will put on net & it is a grate AddressBook for Beginner for creating
database connection throug coding on C#.net Technology it is good for me that
this is my first project with Database connectivity and its a good programming

This is also gives Demo for my 7a47 and 3p38 batch in Aptech Computer Education

     Above Code is not inough for Copy Paste Remembered that :)
Programmed By : Mr. Hiten Patel


             // This is for DataBase Connection 

        private void BtnConnect_Click(object sender, System.EventArgs e)
        {
            this.Hide();
            f1.Show();
            f1.Connection_To_Database(TxtSname.Text,
               TxtDname.Text,TxtUid.Text,TxtPass.Text);        
        }

        
        public void BlankBox()
        {
            string str;
            foreach(Control ctrl in this.Controls)
            {
                str = Convert.ToString(ctrl.GetType());
                if(str == "System.Windows.Forms.TextBox")
                {
                    ctrl.Text = "";
                }
            }
        }
        public void CheckBlank()
        {
            string str;
            foreach(Control ctrl in this.Controls)
            {
                str = Convert.ToString(ctrl.GetType());
                if(str == "System.Windows.Forms.TextBox")
                {
                    if(ctrl.Text.Length == 0)
                    {
                        MessageBox.Show("Cannot Left Blank any Field");
                        ctrl.Focus();
                        break;
                    }
                }
            }
        }

        private void BtnExit_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }
    }
}

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;   //   To Connect with Database u have to use this 

using System.Data.SqlClient; 
//   both namespace other wise it will gives u an error.


        //==================================================

        //Start Sql Connection String and code

            //SqlConnection cnn = new SqlConnection("data source=ntsrv01;" +

            // "initial catalog=7a47;password=7a47;persist security" +

            // " info=True;user id=7a47;workstation" + 

            // " id=WINNT24;packet size=4096");

            SqlConnection cnn = new SqlConnection();
            SqlCommand sc;
            DataSet ds = new DataSet();
            SqlDataAdapter sda =new SqlDataAdapter();
        private System.Windows.Forms.DataGrid dataGrid1;
        private System.Windows.Forms.Label label19;            
        //End Sql Connection String and code

        //==================================================


        public void Connection_To_Database(string sname,
                             string dname,string uid,string pass)
        {
            try
            {
                cnn.ConnectionString = "data source="+ sname 
                   +";initial catalog="+ dname +";user id="+ 
                   uid +";password="+ pass +";persist security info=True";
                cnn.Open();

                this.FriendList();

            }
            catch(Exception Ex)
            {
                MessageBox.Show(Ex.ToString());
            }
        }
        private void BtnAdd_Click(object sender, System.EventArgs e)
        {
            if(BtnAdd.Text == "&Add")
            {
                BtnAdd.Text = "&Save";
                BtnDelete.Text = "&Cancel";
                this.Enable(true);
                TxtName.Focus();
                this.BlankBox();
            }
            else
            {
                BtnAdd.Text = "&Add";
                BtnDelete.Text = "&Delete";
                this.InsertRec(TxtName.Text,TxtAdd.Text,
                   TxtCity.Text,TxtState.Text,TxtCountry.Text,
                   TxtPhone.Text,TxtID.Text);
                this.Enable(false);    
                this.BlankBox();
                this.FriendList();
            }
        }
        private void BtnShow_Click(object sender, System.EventArgs e)
        {
            LstDetails.Items.Clear();
            if(CBAlfa.Text == "Select")
            {
                //MessageBox.Show("Select AlphaBets form the List");

                CBAlfa.Focus();
            }
            else
            {
                this.SelectedFind(CBAlfa.Text);
            }
            
        }
        public void BlankBox()
        {
            string str;
            foreach(Control ctrl in this.Controls)
            {
                str = Convert.ToString(ctrl.GetType());
                if(str == "System.Windows.Forms.TextBox")
                {
                    ctrl.Text = "";
                }
            }
        }
        public void InsertRec(string nm,string add,
           string ct,string st,string country,string ph,string id)
        {
            try
            {
                string sql = "Insert into AddressBook values('"+ 
                   nm +"','"+ add +"','"+ ct +"','"+ st +"','"+ 
                   country +"','"+ ph +"','"+ id +"')";
                //MessageBox.Show(sql);

                sc = new SqlCommand(sql,cnn);
                sc.CommandType = CommandType.Text;
                sc.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        public void Enable(bool flag)
        {
            string str;
            foreach(Control ctrl in this.Controls)
            {
                str = Convert.ToString(ctrl.GetType());
                if(str == "System.Windows.Forms.TextBox")
                {
                    ctrl.Enabled = flag;
                }
            }
        }

        private void BtnDelete_Click(object sender, System.EventArgs e)
        {
            if(BtnDelete.Text == "&Delete")
            {
                this.Enable(false);
                if(LstDetails.SelectedIndex == -1)
                {
                    MessageBox.Show("Oh Sorry u must have to" + 
                       " select your friend name before delete");
                    LstDetails.Focus();
                }
                else
                {
                    DialogResult dr = 
                      MessageBox.Show("Hai man r u sure u wana" + 
                      " delete record of "+
                      LstDetails.SelectedItem.ToString(),
                      "Delete Record Conformation",
                      MessageBoxButtons.YesNo);
                      
                    if(Convert.ToString(dr) == "Yes")
                    {
                        string query = 
                          "delete from addressbook where name = '"+ 
                          LstDetails.SelectedItem.ToString() +"'";
                        this.ExecQuery(query);
                        this.FriendList();
                        this.BlankBox();
                    }
                }
            }
            else
            {
                BtnAdd.Text = "&Add";
                BtnDelete.Text = "&Delete";
                BtnModify.Text = "&Modify";
                this.Enable(false);
                this.BlankBox();
            }
        }
        
        public void ExecQuery(string sql)
        {
            try
            {
                sc = new SqlCommand(sql,cnn);
                sc.CommandType =  CommandType.Text;
                sc.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        public void FriendList()
        {
            LstDetails.Items.Clear();
            try
            {
                string sql = "select * from AddressBook";
                SqlDataAdapter sda = new SqlDataAdapter(sql,cnn);
                DataSet dtset = new DataSet();
                sda.Fill(dtset,"AddressBook");
                DataTable dt = dtset.Tables["AddressBook"];
                dataGrid1.SetDataBinding(dtset,"AddressBook");
                
                foreach(DataRow dtRow in dt.Rows)
                {
                    LstDetails.Items.Add( dtRow["Name"].ToString());
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        public void SelectedFind(string sr)
        {
            try
            {
                string sql = "select * from " + 
                     "AddressBook where name like '"+ sr +"%'";
                //MessageBox.Show(sql);

                SqlDataAdapter sda = new SqlDataAdapter(sql,cnn);
                DataSet dtset = new DataSet();
                sda.Fill(dtset,"AddressBook");
                DataTable dt = dtset.Tables["AddressBook"];
                
                foreach(DataRow dtRow in dt.Rows)
                {
                    LstDetails.Items.Add( dtRow["Name"].ToString());
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void BtnAll_Click(object sender, System.EventArgs e)
        {
            this.FriendList();
            CBAlfa.Text = "Select";
        }

        private void BtnFirst_Click(object sender, System.EventArgs e)
        {
            LstDetails.SelectedIndex=0;
        }

        private void BtnLast_Click(object sender, System.EventArgs e)
        {
            LstDetails.SelectedIndex = LstDetails.Items.Count -1;
        }
        private void BtnModify_Click(object sender, System.EventArgs e)
        {
            if(!(TxtName.Text.Length==0))
            {
                if(BtnModify.Text == "&Modify")
                {
                
                    this.Enable(true);
                    TxtName.Focus();
                    BtnModify.Text = "&Change";
                    BtnDelete.Text = "&Cancel";
                }
                else
                {
                    BtnModify.Text = "&Modify";
                    BtnDelete.Text = "&Delete";
                    string query = "update addressbook set address='"+ 
                       TxtAdd.Text +"',city='"+ TxtCity.Text 
                       +"',state='"+ TxtState.Text +"',country='"+ 
                       TxtCountry.Text +"',phone='"+ TxtPhone.Text 
                       +"',e_mail_id='"+ TxtID.Text 
                       +"' where name like '"+ TxtName.Text +"%'";
                    this.ExecQuery(query);
                    this.Enable(false);

                }
            }
            else
            {
                MessageBox.Show("U Must have to select person" + 
                  " name from the list","Update Error",
                  MessageBoxButtons.OK,MessageBoxIcon.Warning);
                
            }
        }
        private void LstDetails_SelectedIndexChanged(object 
                                       sender, System.EventArgs e)
        {
            try
            {
                //SqlDataAdapter sda = new 

                //  SqlDataAdapter("select * from addressbook" + 

                //  " where name like '"+ 

                //  LstDetails.SelectedItem.ToString() +"%'",cnn);

                SqlDataAdapter sda = new 
                  SqlDataAdapter("select * from addressbook",cnn);
                DataSet dtset = new DataSet();
                sda.Fill(dtset,"AddressBook");

            //    MessageBox.Show("Table in Database = "+

            //                 dtset.Tables.Count.ToString());


                DataTable dt = dtset.Tables["AddressBook"];

            //    MessageBox.Show("Fetched Rows = "

            //            + dt.Rows.Count.ToString());

                
            //    MessageBox.Show(LstDetails.Items.Count.ToString());

            //    MessageBox.Show("Selected Index = "

            //             +LstDetails.SelectedIndex.ToString());

                //DataRow  dr = dt.Rows[0]; 

                DataRow  dr = dt.Rows[LstDetails.SelectedIndex];
                
                TxtName.Text = dr["name"].ToString();
                TxtAdd.Text = dr["address"].ToString();
                TxtCity.Text = dr["city"].ToString();
                TxtState.Text = dr["state"].ToString();
                TxtCountry.Text = dr["country"].ToString();
                TxtPhone.Text = dr["phone"].ToString();
                TxtID.Text = dr["e_mail_id"].ToString();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void BtnAbout_Click(object sender, System.EventArgs e)
        {
            f2.ShowDialog();
        }

        private void BtnExit_Click(object sender, System.EventArgs e)
        {
            DialogResult dr = MessageBox.Show("R u sure u" + 
               " wana quit this application?","Conformation",
               MessageBoxButtons.YesNo,MessageBoxIcon.Stop);
            //DialogResult dr = MessageBox.Show("Su tamare" + 

            //    " aa program bandh karvo chhe..?","Conformation",

            //    MessageBoxButtons.YesNo,MessageBoxIcon.Stop);

            if(Convert.ToString(dr)=="Yes")
            {
                this.Close();
            }
        }

        private void Form1_Load(object sender, System.EventArgs e)
        {

        }
    }
}
// This is for About Dialog Box

private void MailMe_LinkClicked(object sender, 
   System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
    System.Diagnostics.Process.Start("mailto:hpatel4u@hotmail.com");
}
private void ProgInfo_LinkClicked(object sender, 
   System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
{
    System.Diagnostics.Process.Start("IExplore",
                "http://www.geocities.com/hpatel4u");
}
private void Form2_Disposed(object sender, System.EventArgs e)
{
    this.Hide();
}
Best Of Luck in C#.NET [ WinForms ] from Hiten Patel

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here