1

我是 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;
    }
}
4

1 回答 1

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;
}
于 2013-10-21T17:04:37.010 回答