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

时间:2013-05-16 19:22:31

标签: c# asp.net wcf

我想根据wcf服务中检索到的数据来绑定我的gridview。但它只显示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();
}

2 个答案:

答案 0 :(得分:0)

问题是我认为你打电话给不同的服务

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);
   }

答案 1 :(得分:0)

声明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服务显示的代码似乎与您在客户端上调用的方法不同。