Congratulations to all monthly winners of May 2013 !!! They have won INR 2900 cash and INR 27497 worth prize.
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 5121 |  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: 5231 | Category: WPF | Level: Beginner | Points: 250 red flag

Advertisements

Advertisements
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] 




Advertisements

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:2 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

XAML as an Extensible Markup Language has great flexibilities to create objects in XAML itself and do functions like automatic binding, Conversion of Data, etc. Markup Extension allows you to truly extend your markup upto a certain extent to elevate you to write less code and design your application with richer extent. In this article I will discuss how to use existing TypeConverters and MarkupExtensions and also will show you how to create custom implementation of both of them.

The article will guide through the basics of WPF programing with in-depth knowledge about the architecture and the working principles of WPF programs. The article finally creates a sample "Hello World" application to step you into new foundation. Even though I have started from the beginning of WPF, I marked it as Intermediate article, as I will also go indepth of all the techniques while discussing it. This is the first part of the WPF turorial. Stay tune for others.

Ribbon Bar was introduced with Office 2007 has lately been very much popular for latest UI development. Microsoft has replaced the old Menu based application tool with more flexible and easy to learn Ribbon strips in many of its applications. So it is time for other developers to use it in their own applications. The Ribbon UI feature that was released recently bridges this to us.

This is an Application which can change your default Logon Screen of Windows XP. There are many applications that allow you to do this Application’s like Logon Studio etc. I have developed this simple application in WPF using Vb.Net. You can see how i made it by following the description below. The Application does Not use any DLL’s nor does it use any API so it is very easy to understand.

In this article I have showed how you can build pluggable Resources for styles, Languages or any static objects etc. Therefore building a new style doesn't hampers your code and you can easily plugin any new style to the application inspite it is already in production environment. I have added a language converter tool, which will generate multi lingual resources for you.

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 find 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. | 6/20/2013 12:25:22 AM