Silverlight,连接service.cs和数据库的XAML.cs

时间:2011-07-22 06:09:07

标签: silverlight

我找到了一个示例,展示了如何连接到SQL服务器(本地MDF),但它使用数据绑定,我如何以正常方式使用SQL(插入,选择,更新,删除...,sqldatareader,没有绑定),我认为所有SQL人员都应该在service.cs中执行,那么我如何使用我的XAML.cs中的SQL?这是服务代码:

和service.cs:

public class ServiceCustomer : IServiceCustomer
{
    public clsCustomer getCustomer(int intCustomer)
    {
        SqlConnection objConnection = new SqlConnection();
        DataSet ObjDataset = new DataSet();
        SqlDataAdapter objAdapater = new SqlDataAdapter();
        SqlCommand objCommand = new SqlCommand("Select * from Customer where CustomerId=" + intCustomer.ToString());
        objConnection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"].ToString();
        objConnection.Open();
        objCommand.Connection = objConnection;
        objAdapater.SelectCommand = objCommand;
        objAdapater.Fill(ObjDataset);
        clsCustomer objCustomer = new clsCustomer();
        objCustomer.CustomerCode = ObjDataset.Tables[0].Rows[0][0].ToString();
        objCustomer.Customer = ObjDataset.Tables[0].Rows[0][1].ToString();
        objConnection.Close();
        return objCustomer;
    }
}

和我的page.xaml.cs:

public Page()
    {
        InitializeComponent();
        ServiceCustomerClient obj = new ServiceCustomerClient();
        obj.getCustomerCompleted += new EventHandler<getCustomerCompletedEventArgs>(DisplayResults);
        obj.getCustomerAsync(1);
    }
    void DisplayResults(object sender, getCustomerCompletedEventArgs e)
    {
        LayoutRoot.DataContext = e.Result;

    }

如何直接从我的page.xaml.cs中将值插入我的dayabase?如何在服务和xaml对象和函数之间建立连接?

感谢

2 个答案:

答案 0 :(得分:2)

您需要在服务类中添加另一个执行插入的方法,然后将其传递给表单中的值。

public class ServiceCustomer : IServiceCustomer
{
    public clsCustomer getCustomer(int intCustomer)
    {
      ...
    } 

    public void addCustomer(clsCustomer newCustomer)
    {
         //Code to add the customer to the database
    }
}

从您的代码中调用它可以使用以下代码,所有对silverlight中的服务的调用都是异步调用,因此它们在单独的线程中调用,但由于后面的调用没有返回,因此不需要完成的事件处理程序。

public void foo
{
    clsCustomer cust = new clsCustomer();
    //Create your customer object here

    ServiceCustomerClient obj = new ServiceCustomerClient();

    obj.AddCustomerAsync(cust);
}

当您想要添加客户时,可以调用此函数,例如。单击按钮时

public void somebutton_Click(object sender, RoutedEventArgs e)
{
      foo();
}

如果您需要更多信息,请与我们联系。

答案 1 :(得分:2)

Page.xaml.cs文件不会在标准的Silverlight项目中自动生成(超出它通过模板的初始创建),因此您对该类所做的任何更改都将保留。

如果您当前的项目执行了一些xaml类的autogen,那么您可以使用C#Partial Classes in C# Guide的partial class功能添加到类中,而不必担心autogen将删除您的添加。