如何将gridview绑定到wcf服务应用程序

本文关键字:wcf 服务 应用程序 绑定 gridview | 更新日期: 2023-09-27 18:14:13

我想绑定我的gridview基于从wcf服务检索的数据,但它只显示gridview的最后一行数据,而不是显示它们。

这是我的WCF:

try
{
  DSCustomer dscat = new DSCustomer();
   //input is EmpUserID
   cmd.Parameters.AddWithValue("@myuser", id);
   cmd.CommandText = "mystoredproc";
   List<DSCustomer> lst = new List<DSCustomer>();
   SqlDataReader dr = cmd.ExecuteReader();
   while (dr.Read())
   {
      dscat.MyEmpID = Convert.ToInt32(dr["Emp"]);
      dscat.MyEmpName = dr["EmpName"].ToString();
      dscat.MyUnitName = dr["UnitName"].ToString();
      dscat.MyUnitNumber = Convert.ToInt32(dr["Unit"]);
      dscat.MyRole = dr["Role"].ToString();
      dscat.MySurveyStatus = dr["SurveyStatus"].ToString();
      //Add all the returns in to the list from back-end
      lst.Add(dscat);
   }
   //returns to the list
   return lst;
}

这是DScustomer

public class DSCustomer
    {
        //Created properties based on the count of the data that we want to retrieve
        public int MyEmpID { get; set; }
        public string MyEmpName { get; set; }
        public string MyUnitName { get; set; }
        public int MyUnitNumber { get; set; }
        public string MyRole { get; set; }
        public string MySurveyStatus { get; set; }
    }

和default.aspx:

protected void Button1_Click(object sender, EventArgs e)
{
   MyServiceClient client = new MyServiceClient();
   Customer cust = new Customer();
   cust = client.getCategori(tbEmpID.Text);
   var list = new List<Customer> { cust };
   GridView1.DataSource=list;
   GridView1.DataBind();
}

如何将gridview绑定到wcf服务应用程序

问题是我认为你调用了不同的服务

Customer cust = new Customer();
cust = client.getCategori(tbEmpID.Text); // this method only return one customer 
var list = new List<Customer> { cust };
GridView1.DataSource=list;
GridView1.DataBind();

在给定的服务中,您返回List,因此您可以直接将其绑定到DataGrid

GridView1.DataSource=client.getCategori(tbEmpID.Text).AsEnumerable() ;
GridView1.DataBind();

还有一件事,在while循环中创建新的DSCustomer并将其添加到列表末尾

   while (dr.Read())
   {
      DSCustomer cust = new DSCustomer();
      cust.MyEmpID = Convert.ToInt32(dr["Emp"]);
      cust.MyEmpName = dr["EmpName"].ToString();
      cust.MyUnitName = dr["UnitName"].ToString();
      cust.MyUnitNumber = Convert.ToInt32(dr["Unit"]);
      cust.MyRole = dr["Role"].ToString();
      cust.MySurveyStatus = dr["SurveyStatus"].ToString();
      lst.Add(cust);
   }

声明dscat变量的行:

DSCustomer dscat = new DSCustomer();

应该移动到while循环内部。当您可能向lst中添加N个元素时,lst中的每个DSCustomer项将具有与最后添加到lst列表中的项相同的值。

还要注意对WCF服务的调用:

Customer cust = new Customer();
cust = client.getCategori(tbEmpID.Text);

显示您将只获得1个客户对象(不多),然后您从该对象创建一个包含1个项目的列表:

var list = new List<Customer> { cust }; // list only has 1 item.

因此,您为WCF服务显示的代码似乎与您在客户端调用的方法不同。