WPF Data Binding Tutorial 2

Gow.net
Posted by in WPF category on for Beginner level | Points: 250 | Views : 8200 red flag

This articles would be helpful for Beginners to learn WPF data binding.


 Download source code for WPF Data Binding Tutorial 2

WPF Data Binding Tutorial 2


Introduction

  We already saw basics of WPF Binding in Chapter 1 (refer WPF Data Binding Tutorial 1)

    Now we would see the next topic i.e. Using C#[INotifyPropertyChanged].In this chapter, I would cover  usage of INotifyPropertyChanged and how to bind data in WPF. What is the purpose, we need to use INotifyPropertyChanged?  Event is fired  whenever a property Changed. In the following example we see how the UI can know that this event is fired.

           We achieve same resulst in implemented the INotifyPropertyChanged interface in the Student class to generate an event every time the value in the  object's property changes.I have highlighted some codes in below example that"s need to be added to implement INotifyPropertyChanged.

 create class the class name is Student

Student.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data.SqlClient;

using System.Windows;

using System.ComponentModel;

using System.Data;


namespace WPF_Tutorial

{

 public  class Students:INotifyPropertyChanged

   {

       #region Studentdetails

       private int _Rollno;

       public int Rollno

       {

           get{ return _Rollno; }

           set{ _Rollno = value;

      OnPropertyChanged("Rollno");

         }

       }

       private string _FirstName;

       public string FirstName

       {

           get{ return _FirstName; }

           set{ _FirstName = value;

           OnPropertyChanged("FirsName");

           }

       }

       private string _Lastname;

       public string Lastname

       {

          get{ return _Lastname; }

          set{ _Lastname = value;

           OnPropertyChanged("Lastname");

           }

       }

       private string _Colleagename;

       public string Colleagename

       {

           get{ return _Colleagename; }

           set{ _Colleagename = value;

          OnPropertyChanged("Colleagename");

           }

       }

       private int _Marksobtaine;

       public int Marksobtaine

       {

           get{ return _Marksobtaine; }

           set{ _Marksobtaine = value;

           OnPropertyChanged("Marksobtaine");

           }

       }

       private string _Exam;

       public string Exam

       {

          get{ return _Exam; }

           set{ _Exam = value;

           OnPropertyChanged("Exam");

          }

       }

       #endregion

       public Students()

        {

        }


        public SqlCommand objcmd;

       #region insertDetail

       public void Insetrt()

       {

               SqlConnectionobjCon = new SqlConnection("");//connection name

           try

           {

              objCon.Open();

objcmd = new SqlCommand("insert into StudentInformation values(@Rollno,@Fname,@Lname,@Mark,@clgname,@Exam) ", objCon);

               objcmd.Parameters.AddWithValue("@Rollno", Rollno);

               objcmd.Parameters.AddWithValue("@Fname", FirstName);

               objcmd.Parameters.AddWithValue("@Lname", Lastname);

               objcmd.Parameters.AddWithValue("@clgname", Colleagename);

              objcmd.Parameters.AddWithValue("@Mark", Marksobtaine);

               objcmd.Parameters.AddWithValue("@Exam", Exam);

            //On property changed

OnPropertyChanged("Rollno");                OnPropertyChanged("FirstName");                OnPropertyChanged("Lastname");                OnPropertyChanged("Colleagename");                OnPropertyChanged("Marksobtaine");                OnPropertyChanged("Exam");

               objcmd.ExecuteNonQuery();

           }

           catch (Exception ex)

           {

               MessageBox.Show("" + ex);

           }

           finally

           {

               objcmd.Dispose();

               if(objCon.State == ConnectionState.Open)

               {

                   objCon.Close();

                   objCon.Dispose();

               }

           }

           }

       #endregion

       #region LoadDetails

    public void Load()

       {

           SqlConnection objCon = new SqlConnection(""); //connection name

                   objCon.Open();

                   objcmd = new SqlCommand("Select * from StudentInformation where Rollno=@Rollno", objCon);//select command

                   objcmd.Parameters.Add(new SqlParameter("@Rollno", _Rollno));

                   try

                   {

                       SqlDataReader objRDR = objcmd.ExecuteReader();

                       if(objRDR.Read())

                       {

                           _FirstName = objRDR["Fname"].ToString();

                           _Lastname = objRDR["Lname"].ToString();

                           _Colleagename =objRDR["Clgname"].ToString();

                           _Marksobtaine = Convert.ToInt32(objRDR["Mark"]);

                           _Exam = objRDR["Exam"].ToString();

                           //property changed

                       

     OnPropertyChanged("Rollno");                            OnPropertyChanged("FirstName");                            OnPropertyChanged("Lastname");                            OnPropertyChanged("Colleagename");                            OnPropertyChanged("Marksobtaine");                            OnPropertyChanged("Exam");

                       }

                       else

                       {

                         MessageBox.Show("RecordNot Found");

                       }

                   }

                   catch(Exception ex)

                   {

                       MessageBox.Show("" + ex);

                   }

                   finally

                   {

                       objcmd.Dispose();

                       if(objCon.State == ConnectionState.Open)

                       {

                           objCon.Close();

                          objCon.Dispose();

                       }


                   }

           }

       #endregion

       #region UpdateDetails

    public void update()

    {

           SqlConnection objCon = new SqlConnection(""); //connection name

            objCon.Open();

            objcmd = new SqlCommand("update StudentInformation set Fname=@Fname,Lname=@Lname,Mark=@Mark,Clgname=@Clgname,Exam=@Exam where Rollno=@Rollno ", objCon);

            objcmd.Parameters.Add(new SqlParameter("@Rollno", _Rollno));

            try

            {

                objcmd.Parameters.AddWithValue("@Fname", FirstName);

                objcmd.Parameters.AddWithValue("@Lname", Lastname);

                objcmd.Parameters.AddWithValue("@Clgname", Colleagename);

                objcmd.Parameters.AddWithValue("@Mark", Marksobtaine);

                objcmd.Parameters.AddWithValue("@Exam", Exam);

                //propertychanged              

OnPropertyChanged("Rollno");                 OnPropertyChanged("FirstName");                 OnPropertyChanged("Lastname");                 OnPropertyChanged("Colleagename");                 OnPropertyChanged("Marksobtaine");                 OnPropertyChanged("Exam");

                objcmd.ExecuteNonQuery();

            }


            catch (Exception ex)

            {

                MessageBox.Show("" + ex);

            }

            finally

           {

                objcmd.Dispose();

                if(objCon.State == ConnectionState.Open)

                {

                    objCon.Close();

                    objCon.Dispose();

                }

            }

        }

    #region INotifyPropertyChanged Members

 

   public event PropertyChangedEventHandler PropertyChanged;     protected void OnPropertyChanged(string PropertyName)     {         if (this.PropertyChanged != null)         {             PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));         }     }

    #endregion

   }

       #endregio

   }

 

The INotifyPropertyChanged interface implementation allows the class to raise the PropertyChanged event everytime a property value changes. The above class can now be instanitated in the code-behind file of another XAML file (WithoutXAML.xaml) which is similar to that of code listing in below(UI Side).

UI Side:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.ComponentModel;

namespace WPF_Tutorial

{

    public partial class Dataentry : Window

    {

        Students objStudent = new Students();

        public Dataentry()

        {

            InitializeComponent();

        }

        //insert record

        private void btnAdd_Click(object sender, RoutedEventArgs e)

        {

            try

            {

                objStudent.Insetrt();

                MessageBox.Show("Record inserted", "Insert");

                //clearField


                txtRollNo.Text = "";

                txtFirstName.Text = "";

                txtLastName.Text = "";

                txtClgname.Text = "";

                txtexamresult.Text = "";

                txtMarks.Text = "";

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

        //load record

        private void btnLoad_Click(object sender, RoutedEventArgs e)

        {

            if (txtRollNo.Text != null)

            {

                try

                {

                    objStudent.Rollno = Convert.ToInt32(txtRollNo.Text);

                    objStudent.Load();

                }

                catch(Exception ex)

                {

                    MessageBox.Show(ex.Message);

                }

            }

            else

            {

                MessageBox.Show("enter correct code");

            }

        }

        //update record

        private void btnUpdate_Click(object sender, RoutedEventArgs e)

        {

            if (txtRollNo.Text != null)

            {

                try

                {

                    objStudent.Rollno = Convert.ToInt32(txtRollNo.Text);

objStudent.update();

                    MessageBox.Show("Update Record", "Update");

                }

                catch (Exception ex)

                {

                    MessageBox.Show(ex.Message);

                }

            }

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)

        {

            objStudent.PropertyChanged += objStudent_PropertyChanged;

        }

        // Property Changed Event Handler [Pathetic Code!]

       

private void objStudent_PropertyChanged(object sender, PropertyChangedEventArgs e)         {             switch (e.PropertyName)             {                 case "Rollno":                     txtRollNo.Text = Convert.ToString(objStudent.Rollno);                     break;                 case "FirstName":                     txtFirstName.Text =objStudent.FirstName;                     break;                 case "Lastname":                     txtLastName.Text = objStudent.Lastname;                     break;                 case "Colleagename":                     txtClgname.Text = objStudent.Colleagename;                     break;                 case "Marksobtaine":                     txtMarks.Text = Convert.ToString(objStudent.Marksobtaine);                     break;                 case "Exam":                     txtexamresult.Text = objStudent.Exam;                     break;             }         }


        private void txtRollNo_TextChanged(object sender, TextChangedEventArgs e)

        {

            objStudent.Rollno =Convert.ToInt32(txtRollNo.Text);

        }

        private void txtFirstName_TextChanged(object sender, TextChangedEventArgs e)

        {

            objStudent.FirstName = txtFirstName.Text;

        }

        private void txtLastName_TextChanged(object sender, TextChangedEventArgs e)

        {

            objStudent.Lastname = txtLastName.Text;

        }

        private void txtClgname_TextChanged(object sender, TextChangedEventArgs e)

        {

            objStudent.Colleagename =  txtClgname.Text;

        }

        private void txtMarks_TextChanged(object sender, TextChangedEventArgs e)

        {

            objStudent.Marksobtaine = Convert.ToInt32(txtMarks.Text);

        }

        private void txtexamresult_TextChanged(object sender, TextChangedEventArgs e)

        {

            objStudent.Exam = txtexamresult.Text;

        }

    }

}

 

Note that the objStudent_PropertyChanged event handler updates the UI with object values everytime a PropertyChanged event occurs on the Student object. To update the object with UI values, TextChanged event handlers were added for all the textboxes

Note also that the “Insert” "Load" and "Update" button event handlers do not contain the Object-to-UI and UI-to-Object update code as that is now being handled by the event handlers.

However, just because we implemented the
 INotifyPropertyChanged interface in our Student 
class, we were not absolved of the responsibility to write custom event handlers for the object and UI update logic. The whole point of all the above code is to show the tedious coding required to keep the object and UI in sync.

Conclusion


In this articles, we learnt using INotifyPropertyChanged  and how property Changed.Next Chapter, we will see Using C# and XAML [INotifyPropertyChanged and XAML] 




Page copy protected against web site content infringement by Copyscape

About the Author

Gow.net
Full Name: Gowthaman vimal
Member Level:
Member Status: Member
Member Since: 12/13/2011 12:55:26 PM
Country: India
gowthaman8870226416
http://www.dotnetfunda.com
DOTNET Developer

Login to vote for this post.

Comments or Responses

Posted by: debal_saha-9451 on: 1/29/2012 | Points: 25
Good Starting In WPF
I suggest you to more focus in Coding Standards , and also please don't be panic for job , just concentrate in your work , Job will automatically find out .

Login to post response

Comment using Facebook(Author doesn't get notification)