Anirudh’s Weblog


SILVERLIGHT DYNAMIC DATAGRID
September 2, 2011, 9:23 am
Filed under: Silverlight | Tags: ,

This post is the demo for displaying data from WCF in datagrid in silverlight 4. I have used Department data for demo. Please follow points below:

1. Create a class named DepartmentClass.cs (WCF part)
public class DepartmentClass {
public string DepartmentName { get; set; }
public string Description { get; set; }
}
2. Write a select query in .svc.cs file as per below method, we need to define this methid in interface also. The below method is to show how we will send the values to silverlight from WCF. Instead of ObservableCollection we can take list also. da = DataAdapter and con = SqlConnection (WCF part)

public ObservableCollection SelectDepartment(DepartmentClass objDept){
da.SelectCommand = new SqlCommand(“SELECT departmentName, description FROM tblDepartment WHERE isActive=’true’”);
da.SelectCommand.Connection = con;
using (var deptData = da.SelectCommand.ExecuteReader()){
while (deptData.Read()){
_departmentClasses.Add(new DepartmentClass(){
DepartmentName = deptData.GetString(1),
Description = deptData.GetString(2)});
}
}
con.Close();
return _departmentClasses;
}

3. Write following code in .xaml file. In binding we will provide variable name used in Class. (silverlight part)

  <sdk:DataGrid AutoGenerateColumns="False" Grid.Row="6"
            Height="187" HorizontalAlignment="Left"
            Margin="116,13,0,0" Name="dataGrid1"
            VerticalAlignment="Top" Width="433">
   <sdk:DataGrid.Columns>
    <sdk:DataGridTextColumn Width="150" Header="Name"
                  Binding="{Binding DepartmentName}" />
     <sdk:DataGridTextColumn Width="280" Header="Description"
               Binding="{Binding Description}" />
   </sdk:DataGrid.Columns>
  </sdk:DataGrid>

4. Following code will be written in .xaml.cs file in constructor.(silverlight part)

public Department()
{
InitializeComponent();

var depProxy = new AdminServiceReference.IadminClient();
depProxy.SelectDepartmentCompleted +=new EventHandler(depProxy_SelectDepartmentCompleted);
depProxy.SelectDepartmentAsync();
}

private void depProxy_SelectDepartmentCompleted(object sender, SelectDepartmentCompletedEventArgs e)
{
if (e.Result != null)
{
dataGrid1.ItemsSource = e.Result;
}
}

Advertisement

Leave a Comment so far
Leave a comment



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s



Follow

Get every new post delivered to your Inbox.