Sunday, March 24, 2013

WPF - ObservableCollection Binding in WPF

The ObservableCollection<T> is one of the most important features of WPF data binding.Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.it means When an object is added to or removed from an observable collection, the UI is automatically updated. This happens because, when binding to an observable collection, WPF automatically adds a CollectionChanged event handler to the ObservableCollecion's events.

 The main feature of the ObservableCollection<T> are the events it raises when the items it contains change. By implementing the INotifyCollectionChanged and INotifyPropertyChanged interfaces, the collection has events for CollectionChanged and PropertyChanged. All these events are related. The first one is raised whenever something changed in the collection, be it Add, Remove, Move, etc. This also trigger the PropertyChanged event for the Items[] property. When you’re adding or removing items, PropertyChanged is also raised for the Count property.

The ObservableCollection class exists in the System.Collections.ObjectModel namespace.

Let see how to Bind data using ObservableCollection Object in WPF.

Step 1
Download Northwind database from the following link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en

Step 2
Attach a Northwind database into MS-SQL server.

Step 3
Create a WPF Application and give solution name as SolObservableCollection_WPF.

Step 4
Create a New Folder in Solution and give the Folder Name as ORD,it is look like this



Click on Image for Better View


Step 5
Add a Linq to Sql class,Select the ORD folder,right click on Add new Item,select LINQ to SQL classes from installed Visual Studio templates and name it NorthwindDC and click on add button,it is look like this



Click on Image for Better View

Step 6
Open a O/R Designer by double click on NorthwindDC.dbml,it is look like this



Click on Image for Better View



Click on Image for Better View

Visual studio provides an object-relational mapping designer,called the O/R Designer which allows you to visually design the object to database mapping.


Step 7
Create a Employee object that will use LINQ to SQL to map to this table.go to the Server Explorer,select Northwind database,go to the Tables and select Employees table,it is look like this



Click on Image for Better View


Drag and drop Employees table from Server explorer onto the design surface of the O/R Designer,it is look like this


Click on Image for Better View

Step 8
Create a Employee Static Class for retrieving data from Employee Table using Linq or Lambda Expression,it is look like this   
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace SolObservableCollection_WPF
{
    public class Employee
    {
        #region Methods

        /// <summary>
        /// Get Employee Data from Table
        /// </summary>
        /// <returns>List</returns>
        public static List<ORD.Employee> GetEmployeeData()
        {
            try
            {
                ORD.NorthwindDCDataContext DC = new ORD.NorthwindDCDataContext();

                //// Using Linq

                //var Query = from Q in DC.Employees
                //            select new ORD.Employee
                //            {
                //                FirstName = Q.FirstName,
                //                LastName = Q.LastName,
                //                City = Q.City
                //            };


                // Using Lambda Expression

                var Query = DC.Employees.Select(LE => new ORD.Employee() { FirstName=LE.FirstName,LastName=LE.LastName,City=LE.City });

                return Query.ToList<ORD.Employee>();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message); 
            }
        }

        #endregion
    }
}

Step 9
Now add a DataGrid and Button control on window,it is look like this
<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="281*"/>
            <RowDefinition Height="39*"/>
        </Grid.RowDefinitions>
        <DataGrid x:Name="dgEmployee" Grid.Row="0" Grid.Column="0" AutoGenerateColumns="False" CanUserAddRows="False" ItemsSource="{Binding}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="FirstName" Binding="{Binding FirstName}"></DataGridTextColumn>
                <DataGridTextColumn Header="LastName" Binding="{Binding LastName}"></DataGridTextColumn>
                <DataGridTextColumn Header="City" Binding="{Binding City}"></DataGridTextColumn>
            </DataGrid.Columns>


        </DataGrid>

        <Button x:Name="btnAdd" Grid.Row="1" Grid.Column="0" Content="Add" Height="23" Width="100" HorizontalAlignment="Right" Margin="0,0,10,0" Click="btnAdd_Click"></Button>
        
    </Grid>




Click on Image for Better View

Step 10
Bind Employee Data to DataGrid Using ObservableCollection Object,it is look like this
#region Declaration

        private ObservableCollection<ORD.Employee> OcEmployeeObj = null;

        #endregion

        #region Constructor
        
        public MainWindow()
        {
            InitializeComponent();

            try
            {
                // Call Bind Data function in Constructor
                BindData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Bind Employee Data to DataGrid
        /// </summary>
        public void BindData()
        {
            try
            {
                // Create Instance of ObervableCollection class which contains element copied from Specified List
                OcEmployeeObj = new ObservableCollection<ORD.Employee>(Employee.GetEmployeeData());

                if (OcEmployeeObj != null)
                {
                    if (OcEmployeeObj.Count >= 0)
                    {
                        // Bind data to DataGrid Object
                        dgEmployee.DataContext = OcEmployeeObj;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message); 
            }
        }

        #endregion


Step 11
On Button Add Click Event add this following Code,it is look like this
private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Add a data to ObervableCollection Object and DataGrid is Updated Automatically 

                OcEmployeeObj.Add(new ORD.Employee() { FirstName="Kishor",LastName="Naik",City="Thane" });
                OcEmployeeObj.Add(new ORD.Employee() { FirstName = "Ramdas", LastName = "Bhosale", City = "Thane" });
                OcEmployeeObj.Add(new ORD.Employee() { FirstName = "Bhushan", LastName = "Pawar", City = "Thane" });

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message); 
            }
        }


In this way, we can dynamically insert, update and remove items from the DataGrid.

Run the Project.

Output



Click on Image for Better View

After Click on Add Button




Download
Download Source Code

Sunday, March 10, 2013

Asp.net - Send GridView Data through Mail

In this article i will explain how to send GridView data through mail in ASP.net project.

Step 1
Download Northwind database from the following link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en

Step 2
Attach a Northwind database into MS-SQL server.

Step 3
Create a Web Application and give solution name as SolSendGridViewDatain_Email_ASP..net.

Step 4
Add a Gridview and button control on Page,it is look like this
<div>
    
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>

                  <asp:GridView ID="gvEmployee" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" EnableModelValidation="True" ForeColor="Black" GridLines="Vertical">
                        <AlternatingRowStyle BackColor="#CCCCCC" />
                         <Columns>
                            <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
                            <asp:BoundField DataField="LastName" HeaderText="LastName" />
                            <asp:BoundField DataField="City" HeaderText="City" />
                        </Columns>
                        <FooterStyle BackColor="#CCCCCC" />
                        <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                        <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                </asp:GridView>
                <asp:Button ID="btnSendMail" runat="server" Text="Send Mail" OnClick="btnSendMail_Click" />

            </ContentTemplate>
        </asp:UpdatePanel>
           
  
      
    </div>


Click on Image for better View.

Step 5
Add App_Code folder in the solution and add a New Folder inside the App_Code folder and give folder name as ORD,it is look like this



Click on Image for better View.

Step 6
Add a Linq to Sql class,Select the ORD folder,right click on Add new Item,select LINQ to SQL classes from installed Visual Studio templates and name it NorthwindDC and click on add button,it is look like this



Click on Image for better View.

Step 7
Open a O/R Designer by double click on NorthwindDC.dbml,it is look like this



Click on Image for better View.



Click on Image for better View.

Visual studio provides an object-relational mapping designer,called the O/R Designer which allows you to visually design the object to database mapping.

Step 8
Create a Employee object that will use LINQ to SQL to map to this table.go to the Server Explorer,select Northwind database,go to the Tables and select Employees table,it is look like this



Click on Image for better View.

Drag and drop Employees table from Server explorer onto the design surface of the O/R Designer,it is look like this



Click on Image for better View.

Step 9
Create a Employee class in App_Code folder for retriving an employee data from database,it is look like this
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Employee
/// </summary>
public static class Employee
{
    #region Method

    /// <summary>
    /// Get Employee Data
    /// </summary>
    /// <returns></returns>
    public static IList GetEmployeeData()
    {
        try
        {

            ORD.NorthwindDCDataContext DC = new ORD.NorthwindDCDataContext();

            //// Using Linq
            //return (from Q in DC.Employees
            //        select new
            //        {
            //            FirstName = Q.FirstName,
            //            LastName = Q.LastName,
            //            City = Q.City
            //        }).ToList();
            
            //// Using Lambda Expression
            return DC.Employees.Select(LE => new { FirstName = LE.FirstName, LastName = LE.LastName, City = LE.City }).ToList();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }

    #endregion
}

Step 10
Bind Employee data to GridView,it is look like this
protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                BindGridView();
            }
        }
        catch (Exception Ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", "alert('" + Ex.Message + "');", true);
        }
    }

 /// <summary>
    /// Bind Grid View Data
    /// </summary>
    private void BindGridView()
    {
        try
        {
            IList IListObj = Employee.GetEmployeeData();

            if (IListObj != null)
            {
                if (IListObj.Count >= 1)
                {
                    gvEmployee.DataSource = IListObj;
                    gvEmployee.DataBind();
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }

Step 11
In Code Behind,Write ControlContentToHTML function it is look like this
/// <summary>
    /// Output of Server Control Contents
    /// </summary>
    /// <param name="GvObj"></param>
    /// <returns>String</returns>
    private String ControlContentToHTML(GridView GvObj)
    {
        try
        {
            StringBuilder SB = new StringBuilder();
            StringWriter SW = new StringWriter(SB);
            HtmlTextWriter HTW = new HtmlTextWriter(SW);

            GvObj.RenderControl(HTW);

            return SB.ToString();

            
        }
        catch (Exception Ex)
        {
            throw new Exception(Ex.Message); 
        }
    }


RenderControl method implementation, which receives any control and returns its HTML string representation.

Step 12
Override the VerifyRenderingInServerForm Method,it is look like this
public override void VerifyRenderingInServerForm(Control control)
    {
        // base.VerifyRenderingInServerForm(control);
        return;
    }

Above override method Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.if we does not override this above function then it will throw exception at run time.

Error: Control 'gvEmployee' of type 'GridView' must be placed inside a form tag with runat=server.

Step 13
In Code Behind,write SendDataToMail function,it is look like this
/// <summary>
    /// Send a mail 
    /// </summary>
    /// <param name="UserName">Specify the User Name</param>
    /// <param name="Password">Specify the Password</param>
    /// <param name="To">Specify the email address of recipient</param>
    /// <returns>Boolean</returns>
    private Boolean SendDataToMail(String UserName,String Password,String To)
    {
        Boolean Flag = false;
        try
        {
            MailMessage MailMsgObj = new MailMessage(UserName,To);
            MailMsgObj.Subject = "GridView Data";

            MailMsgObj.Body = "Dear Friends.<br/><br/>";
            MailMsgObj.Body += ControlContentToHTML(gvEmployee);
            MailMsgObj.Body += "<br/><br/>";
            MailMsgObj.Body += "Thanks & Regards <br/>";
            MailMsgObj.Body += "Kishor Naik";

            MailMsgObj.IsBodyHtml = true;

            SmtpClient SmtpClntObj = new SmtpClient();
            SmtpClntObj.Host = "smtp.gmail.com";
            SmtpClntObj.Port = 587;
            SmtpClntObj.EnableSsl = true;

            SmtpClntObj.Credentials = new System.Net.NetworkCredential(UserName, Password);

            SmtpClntObj.Send(MailMsgObj);

            Flag = true;

        }
        catch (Exception Ex)
        {
            throw new Exception(Ex.Message);  
        }

        return Flag;
    }


Step 14
On btnSendMail_Click event call SendDataTomail function,it is look like this
protected void btnSendMail_Click(object sender, EventArgs e)
    {
        try
        {
            if (SendDataToMail("kishor.naik011.net@gmail.com", "!@#$%^&*()", "kishor.naik011.net@gmail.com"))
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", "alert('Data has been sent');", true);
            }
        }
        catch (Exception Ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", "alert('" + Server.HtmlEncode(Ex.Message).Replace("'", "\\'") + "')", true);
        }
    }


Run the Project.

Output


Click on Image for better View.


Click on Image for better View.

Download
Download Source Code

Tuesday, March 5, 2013

JQuery - UI Keyboard Plugin

In this article i will explain you how to use JQuery UI Keyboard plugin in ASP.net project Using UI JQuery Plugin.

Step 1
Download UI JQuery Plugin from the following Link
JQuery UI 1.10.1


Step 2
Download UI Keyboard Plugin from the following Link
UI Keyboard Plugin

Step 3
Create a Web Application and give the solution name as SolUIKeyboardPlugin_Jquery

Step 4
Add CSS and Script files which we downloaded from Above Link,it is look like this

CSS

SCRIPT



Click on Image for better View

Step 5
Add two Textbox Control in page,it is look like this
<table border="1" cellpadding="5" cellspacing="5" align="center" width="70%">
                <tr>
                    <td style="width:25%">Alpha Numeric Pad</td>
                    <td style="width:45%">
                        <asp:TextBox ID="txtAlphaNumPad" runat="server" Width="250px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td style="width:25%">Num Pad</td>
                    <td style="width:45%">
                        <asp:TextBox ID="txtNumPad" runat="server" Width="100px"></asp:TextBox>
                    </td>
                </tr>
            </table>




Click on Image for better View

Step 6
Add CSS,JQuery and UI Jquery file Reference inside the head tag of the page,it is look like this
<%-- Jquery CSS --%>
    <link type="text/css" href="css/ui-darkness/jquery-ui-1.10.1.custom.css" rel="stylesheet" rev="Stylesheet"/> 

   <%-- Jquery Plugins--%>
    <script language="javascript" type="text/javascript" src="Script/jquery-1.9.1.js"></script>
    <script language="javascript" type="text/javascript" src="Script/jquery-ui-1.10.1.custom.js"></script>

Step 7
Add UI Keyboard CSS and Jquery file Reference inside the head tag of the page,it is look like this
<%-- UI Keyboard CSS--%>
    <link type="text/css" href="css/keyboard.css" rel="Stylesheet" rev="Stylesheet" />

    <%--UI Keyboad plugins--%>
    <script language="javascript" type="text/javascript" src="Script/jquery.keyboard.js"></script>
    <script language="javascript" type="text/javascript" src="Script/jquery.keyboard.extension-typing.js"></script>

Step 8
Add a below script inside the head tag.it is look like this
<script language="javascript" type="text/javascript">

        $(document).ready(function () {

            try
            {
                // Alpha Numeric Pad

                $("#txtAlphaNumPad").keyboard({
                    autoAccept: true
                }).addTyping();

                // Num Pad

                $("#txtNumPad").keyboard({
                    layout: 'num',
                    restrictInput: true, // Prevent keys not in the displayed keyboard from being typed in 
                    preventPaste: true,  // prevent ctrl-v and right click 
                    autoAccept: true
                }).addTyping();

            }
            catch (E)
            {
                alert(E.message);
            }

        });


    </script>

Here I had written code to show keyboard for one textbox and numberpad for another textbox.

Run the Project.

Demo


Full Code of .ASPX
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Jquery - UI Keyboard</title>

     <%-- Jquery CSS --%>
    <link type="text/css" href="css/ui-darkness/jquery-ui-1.10.1.custom.css" rel="stylesheet" rev="Stylesheet"/> 

   <%-- Jquery Plugins--%>
    <script language="javascript" type="text/javascript" src="Script/jquery-1.9.1.js"></script>
    <script language="javascript" type="text/javascript" src="Script/jquery-ui-1.10.1.custom.js"></script>

   <%-- UI Keyboard CSS--%>
    <link type="text/css" href="css/keyboard.css" rel="Stylesheet" rev="Stylesheet" />

    <%--UI Keyboad plugins--%>
    <script language="javascript" type="text/javascript" src="Script/jquery.keyboard.js"></script>
    <script language="javascript" type="text/javascript" src="Script/jquery.keyboard.extension-typing.js"></script>


    <script language="javascript" type="text/javascript">

        $(document).ready(function () {

            try
            {
                // Alpha Numeric Pad

                $("#txtAlphaNumPad").keyboard({
                    autoAccept: true
                }).addTyping();

                // Num Pad

                $("#txtNumPad").keyboard({
                    layout: 'num',
                    restrictInput: true, // Prevent keys not in the displayed keyboard from being typed in 
                    preventPaste: true,  // prevent ctrl-v and right click 
                    autoAccept: true
                }).addTyping();

            }
            catch (E)
            {
                alert(E.message);
            }

        });


    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
            <table border="1" cellpadding="5" cellspacing="5" align="center" width="70%">
                <tr>
                    <td style="width:25%">Alpha Numeric Pad</td>
                    <td style="width:45%">
                        <asp:TextBox ID="txtAlphaNumPad" runat="server" Width="250px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td style="width:25%">Num Pad</td>
                    <td style="width:45%">
                        <asp:TextBox ID="txtNumPad" runat="server" Width="100px"></asp:TextBox>
                    </td>
                </tr>
            </table>
    </div>
    </form>
</body>
</html>


Output


Click on Image for better View

Download
Download Source Code

Monday, March 4, 2013

WPF - ObjectDataProvider in WPF


The ObjectDataProvider allows you to get information from another class in your application. It adds the following features:

• It can create the object you need and pass parameters to the constructor.
• It can call a method in that object and pass method parameters to it.
• It can create the data object asynchronously. (In other words, it can wait until after the window is loaded and then perform the work in the background.)


The ObjectDataProvider, like all data providers, is designed to retrieve data but not update it. In other words, there’s no way to force the ObjectDataProvider to call a different method in the DB class to trigger an update. This is just one example of how the data provider classes in WPF are less mature than other implementations in other frameworks, such as the data source controls in ASP.NET.

In this Example i will show you that how to take input parameter from Textbox and populating the data to DataGrid according to it using ObjectDataProvider. Our method takes a single parameter which is the letter(s) of the Employee name to locate in Employee table.

Let See how can we use ObjectDataProvider in WPF.

Step 1
Download Northwind database from the following link.

Step 2
Attach a Northwind database into MS-SQL server.

Step 3
Create a WPF Application and give solution name as SolObjectDataProvider.

Step 4
Create a New Folder in Solution and give the Folder Name as ORD,it is look like this



Click on Image for Better View

Step 5
Add a Linq to Sql class,Select the ORD folder,right click on Add new Item,select LINQ to SQL classes from installed Visual Studio templates and name it NorthwindDC and click on add button,it is look like this





Click on Image for Better View

Step 6
Open a O/R Designer by double click on NorthwindDC.dbml,it is look like this



Click on Image for Better View



Click on Image for Better View

Visual studio provides an object-relational mapping designer,called the O/R Designer which allows you to visually design the object to database mapping.

Step 7
Create a Employee object that will use LINQ to SQL to map to this table.go to the Server Explorer,select Northwind database,go to the Tables and select Employees table,it is look like this



Click on Image for Better View

Drag and drop Employees table from Server explorer onto the design surface of the O/R Designer,it is look like this



Click on Image for Better View

Step 8
Create a Employee Class for Searching Employee Name from Employee Table using Linq or Lambda Expression,it is look like this
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SolObjectDataProvider
{
    public class Employee
    {
        #region Method

        public IList SearchEmployeeData(String SearchWord)
        {
            IList Query = null; ;
            try
            {
                ORD.NorthwindDCDataContext DC = new ORD.NorthwindDCDataContext();

                if (SearchWord != String.Empty)
                {
                    //// Using Linq

                    //Query = (from Q in DC.Employees
                    //         where Q.FirstName.Contains(SearchWord.Trim())
                    //         select new
                    //         {
                    //             FirstName = Q.FirstName,
                    //             LastName = Q.LastName,
                    //             City = Q.City
                    //         }).ToList();

                    //// Using Lambda Expresion
                    Query= DC.Employees.Where(LE => LE.FirstName.Contains(SearchWord.Trim())).Select(LE => new { FirstName = LE.FirstName, LastName = LE.LastName, City = LE.City }).ToList();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message); 
            }

            return Query;
        }

        #endregion
    }
}


Now Code Behind Part done Let move the Design section.

Step 9
Now add TextBox and DataGrid Control on window,it is look like this
<Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="7*"/>
        </Grid.RowDefinitions>

        <TextBox x:Name="txtSearch"  Grid.Row="0" Grid.Column="0" Height="25" Width="200" HorizontalAlignment="Left" Margin="10,0,0,0"></TextBox>
        
        <DataGrid x:Name="dgGrid" Grid.Row="1" Grid.Column="0" AutoGenerateColumns="False" CanUserAddRows="False" ItemsSource="{Binding}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="First Name" Binding="{Binding FirstName,IsAsync=True}"/>
                <DataGridTextColumn Header="Last Name" Binding="{Binding LastName,IsAsync=True}"/>
                <DataGridTextColumn Header="City" Binding="{Binding City,IsAsync=True}"/>
            </DataGrid.Columns>

        </DataGrid>
        
    </Grid>



Click on Image for Better View

Step 10
Add the following namespace reference in window tag,it is look like this 
xmlns:Local="clr-namespace:SolObjectDataProvider"
xmlns:System="clr-namespace:System;assembly=mscorlib"

Using this we can access our classes from this above namespace in XAML.

Finally its look like this
<Window x:Class="SolObjectDataProvider.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Local="clr-namespace:SolObjectDataProvider"
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        Title="Object Data Provider" Height="350" Width="525">

</Window>

Step 11
Define the ObjectDataProvider in Window.Resources section in our Window,it is look like this
<Window.Resources>
        <ObjectDataProvider x:Key="ODPEmployee" IsAsynchronous="True" ObjectType="{x:Type Local:Employee}" MethodName="SearchEmployeeData">
            <ObjectDataProvider.MethodParameters>
                <x:Static Member="System:String.Empty" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>

ObjectDataProvider create an instance of Employee class and call the SearchEmployeeData method.The MethodParameters collection has defined a single parameter. This parameter is defaulted to a String.Empty value.

Asynchronous Support
ObjectDataProvider.IsAsynchronous property to true, the ObjectDataProvider performs its work on a background thread. As a result, your interface isn’t tied up while the work is underway. Once the data object has been constructed and returned from the method, the ObjectDataProvider makes it available to all bound elements.

Step 12
Binding the TextBox to the Object Data Provider,it is look like this
<TextBox x:Name="txtSearch"  Grid.Row="0" Grid.Column="0" Height="25" Width="200" HorizontalAlignment="Left" Margin="10,0,0,0" Text="{Binding Source={StaticResource ODPEmployee}, Path=MethodParameters[0], BindsDirectlyToSource=True, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"></TextBox>


In the Text property you set the source of the text box to the static resource called ODPEmployee. This is the key value of the ObjectDataProvider. The Path property is set to the value MethodParameters[0]. This tells WPF to bind to the first parameter in the MethodParameters collection. You also need to specify which event will update the MethodParameters collection. In this example the event is when the Text property changes. By firing the PropertyChanged event you are telling the ObjectDataProvider that it should call the method in the MethodName property again and pass in the data that was just passed into the method parameter from the text box.

BindsDirectlyToSource - When using a DataSourceProvider derived class (for example a
ObjectDataProvider) setting this property to true will bind to the data
source provider object itself, leaving it false will bind to the data
contained in the data source.

Step 13
Bind this ObjectDataProvider  static Resources in  DataContext Property of DataGrid Control,it is look like this

<DataGrid x:Name="dgGrid" Grid.Row="1" Grid.Column="0" AutoGenerateColumns="False" CanUserAddRows="False" ItemsSource="{Binding}" DataContext="{Binding Source={StaticResource ODPEmployee}}">
</DataGrid>


Run the project.

Output

Click on Image for Better View

Full XAML Code
<Window x:Class="SolObjectDataProvider.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Local="clr-namespace:SolObjectDataProvider"
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        Title="Object Data Provider" Height="350" Width="525">
    
    <Window.Resources>
        <ObjectDataProvider x:Key="ODPEmployee" IsAsynchronous="True" ObjectType="{x:Type Local:Employee}" MethodName="SearchEmployeeData">
            <ObjectDataProvider.MethodParameters>
                <x:Static Member="System:String.Empty" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
    
    
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="7*"/>
        </Grid.RowDefinitions>

        <TextBox x:Name="txtSearch"  Grid.Row="0" Grid.Column="0" Height="25" Width="200" HorizontalAlignment="Left" Margin="10,0,0,0" Text="{Binding Source={StaticResource ODPEmployee}, Path=MethodParameters[0], BindsDirectlyToSource=True, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"></TextBox>
        
        <DataGrid x:Name="dgGrid" Grid.Row="1" Grid.Column="0" AutoGenerateColumns="False" CanUserAddRows="False" ItemsSource="{Binding}" DataContext="{Binding Source={StaticResource ODPEmployee}}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="First Name" Binding="{Binding FirstName,IsAsync=True}"/>
                <DataGridTextColumn Header="Last Name" Binding="{Binding LastName,IsAsync=True}"/>
                <DataGridTextColumn Header="City" Binding="{Binding City,IsAsync=True}"/>
            </DataGrid.Columns>

        </DataGrid>
        
    </Grid>
</Window>


Download
Download Source Code