c#如何在datagridview中的windows form app中显示来自wcf服务的sql值

时间:2013-10-21 16:51:30

标签: c# .net sql wcf datagridview

我是wcf的新手,我正在尝试使用wcf连接到sql并在datagridview中显示值,该怎么做?

在IProductsService.cs中,我刚刚做了

[OperationContract]
Products[] getProducts();

和Products.cs

[DataMember]
string productId, productName, location;

public Products(string productId1, string productName1, string location1)
{
    this.productId = productId1;
    this.productName = productName1;
    this.location = location1;                
}       

ProductsService.svc.cs

namespace Products
{
    public Products[] getProducts()
    {
        SqlConnection connection = new SqlConnection( "Data Source=111111;Initial Catalog=11111;User ID=111111;Password=11111");
        connection.Open();

        SqlCommand command = new SqlCommand("SELECT productId, productName, location FROM Products", connection);

        SqlDataReader reader = command.ExecuteReader();

        //Do something here to send value? how?
        return null;
    }
}

1 个答案:

答案 0 :(得分:2)

public List<Prodict> getProducts()
{
    SqlConnection connection = new SqlConnection( "Data Source=111111;Initial Catalog=11111;User ID=111111;Password=11111");
    connection.Open();

    SqlCommand command = new SqlCommand("SELECT productId, productName, location FROM Products", connection);

    var productList = new List<Product>(); //Do Array, if it is better for you.

    using(SqlDataReader rdr = cmd.ExecuteReader())
    {
        while (rdr.Read())
        {
            var product = new Product(rdr.GetValue(0).ToString(),rdr.GetValue(1).ToString(),rdr.GetValue(2).ToString());
            productList.Add(product);
        }
    }

    return productList;
}