WPF Data Binding Tutorial 1

Posted by in WPF category on for Beginner level | Points: 250 | Views : 87107 red flag
Rating: 4 out of 5  
 2 vote(s)

I think this Tutorial Useful for beginners. Next Using C# [INotifyPropertyChanged] Continue in Next Chapter

 Download source code for WPF Data Binding Tutorial 1


Windows Presentation Foundation (WPF) is ships part of .NET frame work and Develop our GUI application 2D,3D,graphics animation and media content using in this WPF.

In advantage of WPF  to less your coding in application.and Easier animation and special effects,Inherent Scalability Inherent scalability 

The developer has to manually write the Code update each UI Elements That Display value stored in the object member .In WPF you can less your code greatly by binding the object directly with the UI using XAML syntax.A developer typically  creates a class to represent an entity (table) in the database,where CRUD operations performed by Calling methods on the objects.

I will Converting 3 different approaches for displaying data in the object onto the UI using WPF

  •    Basic of WPF Binding
  •    Using c#[INotifyPropertyChanged]
  •    Using c# and XAML[INotifyPropertyChanged and XAML]

Create Table: 
 I am going use the same "StudentInformation" table.The Columns for the table are
  •   RollNo(int,not null)
  •  Fname(varchar(10),not null)
  •  Lname(varchar(10),not null)
  •  Clgname(varchar(50),not null)
  •  mark(int,not null)
  •  Exam(varchar(15),not null)     

Basics of WPF Binding:

        First creates the Students class for the table as follows: That Class contain Following Codes

  •      Properties
  •       Insert Record
  •       Update Record
  •       Load Record     

Using a property , a programmer can get access to data members as through  they are public fields, The set and Get methods of property are Contained inside the property declaration.
           private string _myName; 
   // Declare a myName property of type string  
        public string myName                       
           get   { return _myName;}      
           set {  myName = _value; } 

The get method used the keyword return to return  the field's value to caller.The set method use the keyword value to receive the value being passed in from the user.
 A property can omit either a get  clause or the set clause,A property that has get is called  a Read-only set is called write-only property.
   Create the "Students" class for the table as follows,The Set and Get methods of property are continued inside the property declaration  

 class Students


         private int _Rollno;

         public int Rollno// Declare a Rollno property of type int


           get { return _Rollno;}

           set { _Rollno = value;}


       private string _FirstName;

     public string FirstName// Declare a FirstName property of type string 


           get { return _FirstName; }

           set { _FirstName = value; }


       private string_Lastname;

       public string Lastname// Declare a LastName property of type string 


           get { return _Lastname; }

           set { _Lastname = value;}


       private string _Collegename;

       public string Collegename// Declare a CollegeName property of type string 


           get { return _Collegename; }

           set { _Collegename = value;}


       private int _Marksobtaine;

       public int Marksobtaine// Declare a Marksobtaine property of type int 


           get { return _Marksobtaine; }

           set { _Marksobtaine = value;}


       private string _Exam;

       public string Exam// Declare a Exam property of type string 


           get { return _Exam; }

           set { _Exam = value;}



 Insert Record

 Here insert record we already create table “StudenteInformation” table. using “SqlConnection” craete connection and open a connection "objCon.Open();", use  insert query to  insert records using  "SqlCommand".finally execute query and close connection.  
       public void Insetrt()
       SqlConnection objCon = new SqlConnection("[….]");       //create connection       
       objCon.Open();  //open Connection
      objcmd = new SqlCommand("insert into StudentInformation      		values('"+_Rollno+"','"+_FirstName+"','"+_Lastname+"','"+_Marksobtaine 			+"','"+_Colleagename+"','"+_Exam+"')",objCon);

Load Record:
Here view record based on Rollno using "SqlDataReader",The ExecuteReader method of the  SqlCommand objectcmd ,returns a SqlDataReader instance.Creating a SqlDataReader with the new operator doesn't do anything for you.
  You must call ExecuteReader on a command object,like this

  SqlDataReader rdr = cmd.ExecuteReader();

 In our Source Coding Read data from records and binding the value from particular property name

public void Load()     
   {              SqlConnection objCon = new SqlConnection("[….]");
                objcmd = new SqlCommand("Select * from StudentInformation                           	            where  Rollno=@Rollno", objCon);                    //select command                    
                  objcmd.Parameters.Add(new SqlParameter("@Rollno", _Rollno));
                   SqlDataReader objRDR = objcmd.ExecuteReader(); //read data from records(table)
                      if (objRDR.Read())        //Bind records in  property name
                       _FirstName = objRDR["Fname"].ToString();
                       _Lastname = objRDR["Lname"].ToString();
                       _Colleagename = objRDR["Clgname"].ToString();
                       _Marksobtaine = Convert.ToInt32(objRDR["Mark"]);
                       _Exam = objRDR["Exam"].ToString();
                       MessageBox.Show("Record Not Found" );

Update Records:

 Here we update record based on update query, we first assign field to particular  property name example


public void update()
          SqlConnection objCon = new SqlConnection("[…..]");
            objcmd = new SqlCommand("update StudentInformation set       	 				  Fname=@Fname,Lname=@Lname,Mark=@Mark,Clgname=@Clgname", objCon);
               //assign the values and add parameters
               objcmd.Parameters.AddWithValue("@Lname", _Lastname);
                objcmd.Parameters.AddWithValue("@Clgname", _Colleagename);     
               objcmd.Parameters.AddWithValue("@Mark", _Marksobtaine);
UI Side:

 I figured that since it is XAML that we are demonstrating, might as well develop the UI in Microsoft Cider, the  Visual Studio 2010 add-in visual designer for XAML. So, to use the above class the coding for XAML.

<Window x:Class="WPF_Tutorial.Dataentry"



        Title="Dataentry" Height="443" Width="371"

 Background="WhiteSmoke" WindowStartupLocation="CenterScreen">

    <Grid Height="285" Width="286">


            <ColumnDefinition Width="99*"></ColumnDefinition>

            <ColumnDefinition Width="187*"></ColumnDefinition>



            <RowDefinition Height="*"></RowDefinition>

            <RowDefinition Height="*"></RowDefinition>

            <RowDefinition Height="*"></RowDefinition>

            <RowDefinition Height="*"></RowDefinition>

            <RowDefinition Height="*"></RowDefinition>

            <RowDefinition Height="*"></RowDefinition>

            <RowDefinition Height="*"></RowDefinition>


        <TextBlock Margin="54,20,0,0">Rollno::</TextBlock>

        <TextBlock Grid.Row="1" Margin="39,12,0,12">FirstName::</TextBlock>

        <TextBlock Grid.Row="2" Margin="34,9,0,14">LastName::</TextBlock>

 <TextBlock Grid.Row="3" Margin="22,10,185,12"   Grid.ColumnSpan="2">CollegeName::</TextBlock>

        <TextBlock Grid.Row="4" Margin="62,10,185,13" Grid.ColumnSpan="2">Mark::</TextBlock>

        <TextBlock Grid.Row="5" Margin="33,10,3,17">ExamResult::</TextBlock>

        <TextBox Grid.Row="0" Grid.Column="1" Name="txtRollNo" Margin="0,7,40,10"></TextBox>

        <TextBox Grid.Row="1" Grid.Column="1" Name="txtFirstName" Margin="0,7,40,10"></TextBox>

        <TextBox Grid.Row="2" Grid.Column="1" Name="txtLastName" Margin="0,7,40,10"></TextBox>

        <TextBox Grid.Row="3" Grid.Column="1" Name="txtClgname" Margin="0,7,40,10"></TextBox>

        <TextBox Grid.Row="4" Grid.Column="1" Name="txtMarks" Margin="0,7,40,10"></TextBox>

        <TextBox Grid.Row="5" Grid.Column="1" Name="txtexamresult" Margin="0,7,40,10"></TextBox>

        <Button Grid.Row="6" Name="btnAdd" Content="Insert" Margin="12,12,14,0" Click="btnAdd_Click"></Button>

        <Button Grid.Row="6" Grid.Column="1" Name="btnLoad" Content="Load" Margin="13,12,102,0" Click="btnLoad_Click"></Button>

        <Button Grid.Row="6" Grid.Column="1" Name="btnUpdate" Content="Update" Margin="91,12,12,0" Click="btnUpdate_Click"></Button>



Use above coding design our UI in .XAML page

The app lets the user enter the Roll Number for a student, and displays the Student's stats when the "Load" button is clicked. The user can then make any changes in values if required (except for the Roll Number), and click "Update" to make the changes in the database. Nothing fancy here. The code-behind file is pretty straight-forward as well. I have placed a "Check" button on the form to let the user view and compare the values in both, the Student object and on the UI.

In button Click Event no need to write coding, just call object from Student Class and binding the values

create object for Student Class 

Students objStudent = new Students();

objStudent” is object of student class now we call method’s for inside  load, insert and update Button Click Event

like this




After call objects we binding the Textbox  value in particular Property name

In our Source Code 

     //  insert Record

private void btnAdd_Click(object sender,RoutedEventArgs e)   


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

objStudent.FirstName = txtFirstName.Text;

objStudent.Lastname = txtLastName.Text;              

objStudent.Colleagename = txtClgname.Text;        

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

                  objStudent.Exam = txtexamresult.Text;

                 objStudent.Insert();          //call object for insert record    

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


//load record    

private void btnLoad_Click(object sender, RoutedEventArgs e)     


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

                    objStudent.Load(); //call object for Load record    

                    txtFirstName.Text =objStudent.FirstName;

                    txtLastName.Text =objStudent.Lastname;

                    txtClgname.Text =objStudent.Colleagename;

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

                    txtexamresult.Text =objStudent.Exam;          


//update record   

private void btnUpdate_Click(object sender, RoutedEventArgs e)  


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

objStudent.FirstName = txtFirstName.Text;          

objStudent.Lastname = txtLastName.Text;           

objStudent.Colleagename = txtClgname.Text;      

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

objStudent.Exam = txtexamresult.Text;

                objStudent.update();      //call object for update record    

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



This articles helpful for beginners in WPFUsing C# [INotifyPropertyChanged] Continue Next

Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: Gowthaman vimal
Member Level:
Member Status: Member
Member Since: 12/13/2011 12:55:26 PM
Country: India
DOTNET Developer

Login to vote for this post.

Comments or Responses

Posted by: SheoNarayan on: 1/23/2012 | Points: 25
Very good effort, keep it up!
Posted by: Deviprasads on: 7/20/2012 | Points: 25
Buddy, nice article on WPF. 5 out of 5

Login to post response

Comment using Facebook(Author doesn't get notification)