您的位置:首页 > 数据库

Silverlight下的WCF服务之三:调用WCF服务从数据库中取出数据显示在datagrid中

2010-12-09 09:38 489 查看
本文在Silverlight中调用WCF服务,从sql server数据库中取出customers表格数据,并显示show在silverlight的datagrid控件中。

步骤1:创建StudentService wcf服务。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCFDemoService
{
public class StudentService : IStudentService
{
public List<Student> GetStudents(int NoOfRecords)
{
List<Student> studentList = new List<Student>();
Random rd = new Random();
for (int Idex = 1; Idex <= NoOfRecords; Idex++)
{
Student student = new Student();
student.StudentID = Idex;
student.StudentName = "Student Name No." + Idex.ToString();
student.Score = (int) (60 + rd.NextDouble() * 40);
student.EvaluationTime = System.DateTime.Now;
studentList.Add(student);
}
return studentList;
}
}
}


实现IStudentService接口如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCFDemoService
{
[ServiceContract]
public interface IStudentService
{
[OperationContract]
List<Student> GetStudents(int NoOfRecords);
}
[DataContract]
public class Student
{
private int studentID;
private string studentName;
private int score;
private DateTime evaluationTime;
[DataMember(Order = 1)]
public int StudentID { get { return studentID; } set { studentID = value; } }
[DataMember(Order = 2)]
public string StudentName { get { return studentName; } set { studentName = value; } }
[DataMember(Order = 3)]
public int Score { get { return score; } set { score = value; } }
[DataMember(Order = 4)]
public DateTime EvaluationTime { get { return evaluationTime; } set { evaluationTime = value; } }
}
}


步骤2:创建Silverlight项目,并引用刚才创建的WCF服务。

xaml界面有一个button,一个datagrid控件。点击按钮调用WCF服务,从数据库中取出表格,并显示在datagrid控件中,如下:

<UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  x:Class="SilverlightWCFDemo.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
<Grid x:Name="LayoutRoot" Margin="20, 20, 20, 20">

<Button x:Name="btnMakeWCFCall" FontSize="12"
Content="Make WCF Call"
HorizontalAlignment="Right"
VerticalAlignment="Center"
Click="btnMakeWCFCall_Click"/>

<StackPanel HorizontalAlignment="Center" Margin="0,20,0,20" Height="1200" >
<data:DataGrid Name="dataGrid1" Height="1000"
Width="600" AutoGenerateColumns="True"
HorizontalAlignment="Center" />

</StackPanel>
</Grid>

</UserControl>


后台C#代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ServiceModel;
using System.Collections.ObjectModel;
using System.Text;
using SilverlightWCFDemo.StudentService;
namespace SilverlightWCFDemo
{
public partial class MainPage : UserControl
{
private IDictionary<string, string> DeploymentConfigurations;
public MainPage()
{
InitializeComponent();
App application = (App)Application.Current;
DeploymentConfigurations = application.DeploymentConfigurations;
StringBuilder SB = new StringBuilder();
SB.Append("Developed by ");
SB.Append(DeploymentConfigurations["Author"]);
SB.Append(" on ");
SB.Append(DeploymentConfigurations["DevelopmentTime"]);
//lblAuthorInformation.Text = SB.ToString();
this.Cursor = Cursors.Arrow;
}
private void btnClearWCFCallResult_Click(object sender, RoutedEventArgs e)
{
//dgResult.ItemsSource = null;
GC.Collect();
}
private void btnMakeWCFCall_Click(object sender, RoutedEventArgs e)
{

//ComboBoxItem aItem = (ComboBoxItem)cmbNoOfStudentRecords.SelectedItem;
//if (aItem.Tag.ToString() == "*")
//{
//    MessageBox.Show("Please select the number of the student records to retrieve");
//     return;
//}
int NoofStudentRecord = 20;//System.Convert.ToInt16(aItem.Tag.ToString());

AsyncCallback aSyncCallBack = delegate(IAsyncResult result)
{
ObservableCollection<StudentService.Student> studentList;

try
{
studentList = ((StudentService.IStudentService)result.AsyncState).EndGetStudents(result);
Deployment.Current.Dispatcher.BeginInvoke(() => { dataGrid1.ItemsSource = studentList.ToList();});

}
catch (Exception ex)
{
Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(ex.Message));
return;
}

};

WCFServiceFactory.GetInstance().iStudentService.BeginGetStudents(
NoofStudentRecord, aSyncCallBack, WCFServiceFactory.GetInstance().iStudentService);
}
void proxy_GetStudentsCompleted(object sender, GetStudentsCompletedEventArgs e)
{
//throw new NotImplementedException();
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);  // bare bones
return;
}
//ObservableCollection<StudentService.Student> studentList = new ObservableCollection<Student>();
//studentList = e.Result;
//dgResult.ItemsSource = studentList.ToList();
List<Data> source = new List<Data>();
int itemsCount = 100;
for (int i = 0; i < itemsCount; i++)
{
source.Add(new Data()
{
Column1 = "Data" + i,
Column2 = "Second Column" + i,
Column3 = i,
Column4 = (i % 2 == 0)
});
}
// Bind the datagrid
//dgResult.ItemsSource = source;

}
}
}


结果如下:



点击按钮,调用WCF服务,结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: