Introducing DotNetFunda.com on mobile http://m.dotnetfunda.com ! Be with DotNetFunda.com on the go !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 29877 |  Welcome, Guest!   Register  Login
Home > Articles > WPF > WPF Data Binding Tutorial 2

WPF Data Binding Tutorial 2

Article posted by Gow.net on 1/21/2012 | Views: 2731 | Category: WPF | Level: Beginner | Points: 250 red flag


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

Download


 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] 




If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:0 year(s)
Home page:http://www.dotnetfunda.com
Member since:Tuesday, December 13, 2011
Level:Starter
Status: [Member]
Biography:DOTNET Developer
 Responses
Posted by: Debal_saha@yahoo.com | Posted on: 29 Jan 2012 11:39:47 PM | 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 .

>> Write Response - Respond to this post and get points
Related Posts

Windows 7 came up with lots of goodies including better resource management, better performance, jumplist management, multitouch functionality & many more. Here I will discuss on developing a simple multitouch application using .Net 3.5 SP1.

This article describes the basics of WPF application, how you can deal with layout, placements of controls and position. The article also introduces few uncommon controls like UniformGrid, InkCanvas etc.

In this article, I have specified how you could use Style, Triggers and animation in your WPF application to make your application more attractive, interactive and user friendly.

Events are not a new part to know about if you are working in Microsoft Technologies, but now when WPF has introduce a new concept called as Rounted Events, we will look into the same.

WPF has an inbuilt feature of Spellchecking. In this article I have explored the SpellCheck functionality of WPF TextBoxBase object. CustomDictionaries introduced with WPF 4.0 is also discussed with this article

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/28/2012 11:57:11 AM