Silverlight / WPF - How to bind data from web service to datagrid of wpf

Asked By weizz on 31-Jul-11 11:22 PM
Hi all,

My question is how to bind data which is stored in Microsoft SQL Server 2008 and return as dataset in the web wervice to the datagrid control in wpf application. Please guide me. Thanks in advance.
TSN ... replied to weizz on 31-Jul-11 11:28 PM
hi..

here is the solution check this out..

WINDOWS.XAML

<Window x:Class="IssueAddinOutlook.Window1"
  Title="Issue List" Height="424" Width="696">
 
<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="102*" />
    <ColumnDefinition Width="590*" />
  </Grid.ColumnDefinitions>
  <Label Height="41" Margin="172,0,265,0" Name="label1" VerticalAlignment="Top" FontSize="22" Grid.Column="1">Issue List</Label>
 
  <dg:DataGrid x:Name="dataGrid" AutoGenerateColumns="True"
     AlternationCount="2"
 
     HeadersVisibility="All"
     HorizontalGridLinesBrush="#DDDDDD"
     VerticalGridLinesBrush="#DDDDDD" Grid.ColumnSpan="2" Margin="0,0,28,26">
 
    <dg:DataGrid.Columns>
      <dg:DataGridTextColumn Header="ID Issue" Binding="{Binding Path=Id}" />
      <dg:DataGridTextColumn Header="Order Id" Binding="{Binding Path=OrderId}" />
      <dg:DataGridTextColumn Header="Is Done" Binding="{Binding Path=IsDone}" />
      <dg:DataGridTextColumn Header="Final Comment" Binding="{Binding Path=FinalComment}" />
      <dg:DataGridTextColumn Header="Actual Hours" Binding="{Binding Path=ActualHours}" />
      <dg:DataGridTextColumn Header="Group Id" Binding="{Binding Path=GroupId}" />
    </dg:DataGrid.Columns>
  </dg:DataGrid>
</Grid>
<Window.Resources>
  <Style x:Key="columnHeaderStyle" TargetType="{x:Type dg:DataGridColumnHeader}">
    <Setter Property="Background">
      <Setter.Value>
        <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
          <LinearGradientBrush.GradientStops>
            <GradientStop Color="Navy" Offset="0" />
            <GradientStop Color="LightBlue" Offset="1" />
          </LinearGradientBrush.GradientStops>
        </LinearGradientBrush>
      </Setter.Value>
    </Setter>
    <Setter Property="Foreground" Value="White" />
  </Style>
  <Style x:Key="rowStyle" TargetType="dg:DataGridRow">
    <Setter Property="FontFamily" Value="Verdana" />
    <Setter Property="FontSize" Value="10" />
    <Style.Triggers>
      <Trigger Property="AlternationIndex" Value="0">
        <Setter Property="Background" Value="White" />
      </Trigger>
      <Trigger Property="AlternationIndex" Value="1">
        <Setter Property="Background" Value="#DDDDDD" />
      </Trigger>
      <Trigger Property="IsMouseOver" Value="True">
        <Setter Property="Background" Value="#BBBBBB" />
      </Trigger>
    </Style.Triggers>
  </Style>
</Window.Resources>

And the WINDOWS.XAML.CS

Issuereference.Tasks issueRef = new Issuereference.Tasks();
Issuereference.TASK[] tasksList = issueRef.GetTasks(39);
dataGrid.ItemsSource = tasksList.ToList();

Web Star replied to weizz on 31-Jul-11 11:29 PM

In WPF, you bind to objects returned by web service method calls the same way you bind to any other objects. To demonstrate, we’ll walk through a simple application that consumes the MSDN/TechNet Publishing System (MTPS) Content Service, discussed here. Our application implements a very simple scenario that retrieves the list of languages supported by a given document.

 

Create a Reference to the Web Service

The first step is to create a reference to the MTPS web service. To create a web reference using Visual Studio:

 

  1. Open your project in Visual Studio.
  2. From the Project menu, click Add Web Reference.
  3. In the dialog box, set the URL to the following:http://services.msdn.microsoft.com/contentservices/contentservice.asmx?wsdl
  4. Press Go, then Add Reference, to create the web reference.

 Call the Web Service and Set the DataContext

We are now ready to call the GetContent web service method and bind to the returned object. All we need to do is call the web service and set the DataContext property of the appropriate window or control to the object returned by the web service method. In this app, we provide a specific contentIdentifier for our simple request. (If you are interested in creating other requests, check out the MTPS Web Services document.)

 

The following code shows you how to do that:

 

// 1. Include the web service namespace

using BindtoContentService.com.microsoft.msdn.services;

      . . .

    // 2. Set up the request object

    // To use the MSTP web service, we need to configure and send a request

    // In this example, we create a simple request using the ID of the XmlReader.Read method page

    getContentRequest request = new getContentRequest();

    request.contentIdentifier = "abhtw0f1";

 

    // 3. Create the proxy

    ContentService proxy = new ContentService();

 

    // 4. Call the web service method and set the DataContext of the Window

    // (GetContent returns an object of type getContentResponse)

    this.DataContext = proxy.GetContent(request);

 

Create the Bindings

Now that the DataContext has been set, we can create the bindings. In the following XAML, we bind the TextBlock to the contentGuid. We want the ItemsControl to show the list of available languages of the requested content, and so we have the ItemsControl bind to and display the locale values of availableVersionsAndLocales. Take a look at this document to see the structure of getContentResponse.

 

    <TextBlock Text="Content Guid:"/>

    <TextBlock Text="{Binding Path=contentGuid}" />

    <TextBlock Text="Available Locales:"/>

    <ItemsControl ItemsSource="{Binding Path=availableVersionsAndLocales}"

              DisplayMemberPath="locale"/>


weizz replied to TSN ... on 31-Jul-11 11:36 PM
Hi Carlos,

Thanks for your reply.
I would like to know is that a must to include the toolkit below?

Forgot to state that the the data that I need to retrieve is from remote computer.So the way of binding is still the same?
Jitendra Faye replied to weizz on 31-Jul-11 11:39 PM

Follow these steps=

Step 1: Click Start All Program à Microsoft Visual Studio 2010 à Microsoft Visual Studio 2010

Step 2: Click “New Project”

Step 3: Under “Visual C#” à Windows à WPF Application

Give application name for your new WPF applications, mention the location and solution name.

 

Start Designing and Programming using WPF

Designing windows or web application is quite easy and interesting also. Let’s start designing our first application using WPF.


WPF
will generate XAML tags similar to HTML. Here I have used the below mentioned tools for design:

  • fName_lbl -> “First Name” Label
  • fName_Txt -> Textbox
  • lName_lbl -> “Last Name” Label
  • lName_Txt -> Textbox
  • DOB_lbl -> “Date of Birth” Label
  • DOB_Txt -> Date Picker
  • City_lbl -> “City” Label
  • City_Txt -> Combo Box
  • New_Btn -> “New” Button
  • Add_Btn -> “Add” Button
  • Del_Btn -> “Delete” Button
  • Update_Btn -> “Update” Button

Datagrid1


Data
binding to “Datagrid1” in WPF is simple, in this example, I have used ADO.NET for binding.


<
datagrid width="481" height="199" name="dataGrid1" selectedcellschanged="dataGrid1_SelectedCellsChanged" canuserresizerows="False" loaded="dataGrid1_Loaded" itemssource="{Binding Path=MyDataBinding}" verticalalignment="Top" margin="14,65,0,0" horizontalalignment="Left" grid.row="4" autogeneratecolumns="False"> <datagrid.columns> <datagridtextcolumn width="120" isreadonly="True" header="First Name" binding="{Binding Path=fName}"> <datagridtextcolumn width="110" isreadonly="True" header="Last Name" binding="{Binding Path=lName}"> <datagridtextcolumn width="150" isreadonly="True" header="Date Of Birth" binding="{Binding Path=DOB}"> <datagridtextcolumn width="90" isreadonly="True" header="City" binding="{Binding Path=City}"> </datagridtextcolumn></datagridtextcolumn>< /datagridtextcolumn></datagridtextcolumn></datagrid.columns> </datagrid>

We can bind the data to datagrid by assigning it to datagrid’s “ItemsSource” and mention the data path which will connect to database to get the data. This is an add on feature in WPF.

App.config is a configuration file which will have the setting and other stuff for an application. Here, I have used this to store the database connectionstring and it is as follows:

<configuration>
     <connectionstrings>
         <add name="ConnectionString1" 
         connectionstring="Data Source=(Database file location goes here) 
         \DatabindusingWPF.sdf; Password=test@123; Persist Security Info=False;">
        </add></connectionstrings>
</configuration>

Here, I have used SQL Server Compact 3.5 sp1 as my data source so we have to give the exact path of the database file where it is stored. (Note: You need to give exact path of the database file to make this code work).

Whenever we add, delete, update datagrid has to be changed accordingly, so I created a public method named “BindGrid()”.

// Establishing Connection String from Configuration File
string _ConnectionString = ConfigurationManager.ConnectionStrings
			["ConnectionString1"].ConnectionString;
public void BindGrid()
 {            
    SqlCeConnection _Conn = new SqlCeConnection(_ConnectionString);
    // Open the Database Connection
    _Conn.Open();
    SqlCeDataAdapter _Adapter = new SqlCeDataAdapter("Select * from Details", _Conn);
    DataSet _Bind = new DataSet();
    _Adapter.Fill(_Bind, "MyDataBinding");                   
    dataGrid1.DataContext = _Bind;
    // Close the Database Connection
    _Conn.Close();
   }

In the above, I have shown a very simple way to get the SQL connection string which will connect to database and used dataset to bind the data to datagrid. The below code will add new record using the values from the textbox.

Follow this link-

http://www.codeproject.com/KB/cs/DatagridonWPF.aspx


Hope this will help you.

Reena Jain replied to weizz on 31-Jul-11 11:46 PM
Hi,

Here is simple code for you

<UserControl x:Class="SQLDataBinding.MainPage"
  mc:Ignorable="d"
  d:DesignHeight="300" d:DesignWidth="400" xmlns:my="clr-namespace:VIBlend.Silverlight.Controls;assembly=VIBlend.Silverlight.DataGrid" xmlns:my1="clr-namespace:VIBlend.Silverlight.Controls;assembly=VIBlend.Silverlight.Editors">
 
  <Grid x:Name="LayoutRoot" Background="White">
    <my:DataGrid AutoGenerateColumns="True" BorderBrush="LightGray" BorderThickness="2" Height="276" HorizontalAlignment="Left" Margin="24,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="287" />
    <my1:Button Content="Load Data" Height="23" HorizontalAlignment="Left" Margin="316,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
  </Grid>
</UserControl>

try this and let me know
dipa ahuja replied to weizz on 01-Aug-11 10:34 AM
Hi.. If you are aware with the binding of C# in dataGridveiw then try this simple code, which is almost similar to that, with little change in properties..

Step 1 : Write this code in .cs

public Form1()
{
  InitializeComponent();
  string connString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"; 
  SqlDataAdapter da = new SqlDataAdapter("Select * from emp1", connString);
  DataSet ds = new DataSet();
  
  da.Fill(ds);
  dataGrid1.DataContext = ds;      
}
Step 2 : set the properties of dataGrid this way:

<DataGrid  ItemsSource="{Binding Path=Tables[0]}"   
      Margin="10" 
      x:Name="dataGrid1"   
      ColumnHeaderHeight="30" AutoGenerateColumns="True"   
      CanUserSortColumns="False">
</DataGrid>

Devil Scorpio replied to weizz on 01-Aug-11 11:52 AM
Hi,

You could add the reference to your web service in your WPF application through Visual Studio at first. (You might follow the steps of the following link: Binding to Web Services )

Then, just call your method to retrive the DataTable from the returned dataset, convert the DataTable to DataView through the AsDataView method, and set the dataview to your datagrid's ItemsSource property.

For example:

myDataGrid.ItemsSource = myDataSet.Tables[ myIndex ].AsDataView();
Radhika roy replied to weizz on 01-Aug-11 01:18 PM

 Follow this steps-

App.xaml

This looks like :

<Application x:Class="DataBind.App"
  xmlns
="http://schemas.microsoft.com/netfx/2007/xaml/presentation"
  xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
  StartupUri
="Window1.xaml"
  
>
  
<Application.Resources>
     
  
</Application.Resources>
</Application>

I made no changes to this template generated code or to App.xaml.cs.

 

Window1.xaml.cs

The C# code to extract the data from the database and fill the DataTable is almost identical to that for NET 2.0 except for setting the DataContext. Microsoft says that Data context is a concept that allows elements to inherit information from their parent elements about the data source that is used for binding, as well as other characteristics of the binding, such as the path. It seems you can set the DataContext in the XAML file, but it seems simpler in this case to set it within the .cs file.

using System;
using 
System.Data;
using 
MySql.Data.MySqlClient;

namespace 
DataBind
{

  
/// <summary>
  /// Interaction logic for Window1.xaml
  /// </summary>

  
public partial class Window1 : System.Windows.Window
  {
    
public Window1()
    {
      InitializeComponent()
;

      
DataTable contentsTable = new DataTable();

       
//Set the connection String
      
String connString "server=127.0.0.1;uid=root;pwd=password;database=contents;";
        
      
//Set the query
      
String query "SELECT assetno, item, descr, serialno, purchfrom, manuf FROM contents";

       
// Fill the Set with the data
      
using (MySqlConnection conn = new MySqlConnection(connString))
      {
        
//Passing the query and connection String
        
MySqlDataAdapter da = new MySqlDataAdapter(query, conn);
        
da.Fill(contentsTable);
      
}

       
// Set the Data Context
      
DataContext contentsTable;       
    
}
  }
}  

 

Window1.xaml

The following is about as simple as I could make it, just to demonstrate Data Binding in WPF. Typically, each binding has four components; a binding target object, a target property (the text property of the TextBox), a binding source, and a path to the value in the binding source to use (note - in this simple case the Path property value is the name of the source object to use for binding). Once you have this concept then the next stage is to use DataTemplates which help to make the presentation of your data objects a lot more appealing and also assist in setting a common look across your Forms.

<Window x:Class="DataBind.Window1"  
   xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"  
   Title
="Data Binding Example" Height="220" Width="300"
   WindowStartupLocation
="CenterScreen">
  
<Grid>  
     
<Grid.RowDefinitions>  
      
<RowDefinition/>  
      
<RowDefinition/>  
      
<RowDefinition/>  
      
<RowDefinition/>  
      
<RowDefinition/> 
      
<RowDefinition/>
     
</Grid.RowDefinitions>  
    
    
<Grid.ColumnDefinitions>  
     
<ColumnDefinition Width="75"/>  
     <
ColumnDefinition/>  
    
</Grid.ColumnDefinitions>  
   
    
<Label>Assetno:</Label>  
    
<TextBox Grid.Column="1" Text="{Binding Path=assetno}"/>  
    <
Label Grid.Row="1">Item:</Label>  
    
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding item}"/>  
    <
Label Grid.Row="2">Description:</Label>  
    
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding descr}"/>  
    <
Label Grid.Row="3">Serialno:</Label>  
    
<TextBox Grid.Row="3" Grid.Column="1" Text="{Binding serialno}"/>  
    <
Label Grid.Row="4">Purch. from:</Label>  
    
<TextBox Grid.Row="4" Grid.Column="1" Text="{Binding purchfrom}"/> 
    <
Label Grid.Row="5">Manuf:</Label>  
    
<TextBox Grid.Row="5" Grid.Column="1" Text="{Binding manuf}"/> 
   </
Grid>  

</Window>

Follow this link also-
http://homepage.ntlworld.com/herring1/databind.html
Radhika roy replied to weizz on 01-Aug-11 01:19 PM

App.xaml

This looks like :

<Application x:Class="DataBind.App"
  xmlns
="http://schemas.microsoft.com/netfx/2007/xaml/presentation"
  xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
  StartupUri
="Window1.xaml"
  
>
  
<Application.Resources>
     
  
</Application.Resources>
</Application>

I made no changes to this template generated code or to App.xaml.cs.

Window1.xaml.cs

The C# code to extract the data from the database and fill the DataTable is almost identical to that for NET 2.0 except for setting the DataContext. Microsoft says that Data context is a concept that allows elements to inherit information from their parent elements about the data source that is used for binding, as well as other characteristics of the binding, such as the path. It seems you can set the DataContext in the XAML file, but it seems simpler in this case to set it within the .cs file.

using System;
using 
System.Data;
using 
MySql.Data.MySqlClient;

namespace 
DataBind
{

  
/// <summary>
  /// Interaction logic for Window1.xaml
  /// </summary>

  
public partial class Window1 : System.Windows.Window
  {
    
public Window1()
    {
      InitializeComponent()
;

      
DataTable contentsTable = new DataTable();

       
//Set the connection String
      
String connString "server=127.0.0.1;uid=root;pwd=password;database=contents;";
        
      
//Set the query
      
String query "SELECT assetno, item, descr, serialno, purchfrom, manuf FROM contents";

       
// Fill the Set with the data
      
using (MySqlConnection conn = new MySqlConnection(connString))
      {
        
//Passing the query and connection String
        
MySqlDataAdapter da = new MySqlDataAdapter(query, conn);
        
da.Fill(contentsTable);
      
}

       
// Set the Data Context
      
DataContext contentsTable;       
    
}
  }
}  

Window1.xaml

The following is about as simple as I could make it, just to demonstrate Data Binding in WPF. Typically, each binding has four components; a binding target object, a target property (the text property of the TextBox), a binding source, and a path to the value in the binding source to use (note - in this simple case the Path property value is the name of the source object to use for binding). Once you have this concept then the next stage is to use DataTemplates which help to make the presentation of your data objects a lot more appealing and also assist in setting a common look across your Forms.

<Window x:Class="DataBind.Window1"  
   xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"  
   Title
="Data Binding Example" Height="220" Width="300"
   WindowStartupLocation
="CenterScreen">
  
<Grid>  
     
<Grid.RowDefinitions>  
      
<RowDefinition/>  
      
<RowDefinition/>  
      
<RowDefinition/>  
      
<RowDefinition/>  
      
<RowDefinition/> 
      
<RowDefinition/>
     
</Grid.RowDefinitions>  
    
    
<Grid.ColumnDefinitions>  
     
<ColumnDefinition Width="75"/>  
     <
ColumnDefinition/>  
    
</Grid.ColumnDefinitions>  
   
    
<Label>Assetno:</Label>  
    
<TextBox Grid.Column="1" Text="{Binding Path=assetno}"/>  
    <
Label Grid.Row="1">Item:</Label>  
    
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding item}"/>  
    <
Label Grid.Row="2">Description:</Label>  
    
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding descr}"/>  
    <
Label Grid.Row="3">Serialno:</Label>  
    
<TextBox Grid.Row="3" Grid.Column="1" Text="{Binding serialno}"/>  
    <
Label Grid.Row="4">Purch. from:</Label>  
    
<TextBox Grid.Row="4" Grid.Column="1" Text="{Binding purchfrom}"/> 
    <
Label Grid.Row="5">Manuf:</Label>  
    
<TextBox Grid.Row="5" Grid.Column="1" Text="{Binding manuf}"/> 
   </
Grid>  

</Window>

Follow this link also-

http://homepage.ntlworld.com/herring1/databind.html