在客户端调用WebService服务获取数据
采用WebService服务获取NorthWind数据库中Employees表数据 ? WebSercive服务获取表数据,并返回一个XML类型的字符串 ? WebSercive返回方法 [WebMethod] public string getEmployees() { StringBuilder reString = new StringBuilder(); ? string constr = "server=.;database = Northwind;uid=sa;pwd=sa"; SqlConnection con = new SqlConnection(constr); SqlDataAdapter sda = new SqlDataAdapter("select * from Employees",con); DataSet ds = new DataSet(); DataTable dt; ? sda.Fill(ds,"employees"); dt = ds.Tables["employees"]; ? reString.AppendLine("<Root>"); ? for (int i = 0; i < dt.Rows.Count; i++) { reString.AppendLine("<employees>"); for (int j = 0; j < ds.Tables["employees"].Columns.Count - 1; j++) { reString.Append("<"+ds.Tables["employees"].Columns[j].ColumnName + ">"); reString.Append(dt.Rows[i][j].ToString()); reString.AppendLine("</" + ds.Tables["employees"].Columns[j].ColumnName + ">"); } reString.AppendLine("</employees>"); ? } ? reString.AppendLine("</Root>"); ? return reString.ToString(); } ? 在客户端调用WebSercive服务前,需要先添加Web引用 ? 我这儿是在WinForm里调用的 在窗口控件DataGridView中发表形式显示返回的Employees表数据 因为由WebSercive服务获取的是XML形式的字符串,在显示的时候需要还原成表 ? ? Form端代码如下: dataGridView1.Columns.Clear(); localhost.WebService w = new WindowsApplication1.localhost.WebService(); ? XmlDocument doc = new XmlDocument(); doc.LoadXml(w.getEmployees()); ? XmlNode xn = doc.DocumentElement; ? XmlNodeList xnList = xn.FirstChild.ChildNodes; ? for (int i = 0; i < xnList.Count; i++) { ??? //在DataGridView中添加标题档 ??? DataGridViewTextBoxColumn DGV = new DataGridViewTextBoxColumn(); DGV.HeaderText = xnList.Item(i).Name; this.dataGridView1.Columns.AddRange(new DataGridViewColumn[] { DGV }); } ? XmlNodeList xnList2 = xn.ChildNodes; ? for (int i = 0; i < xnList2.Count; i++) { ??? //新添加一行数据 不然会报错 dataGridView1.Rows.Add(); for (int j = 0; j < xnList.Count; j++) ????{ ???????? //声明数据行 ???? DataGridViewTextBoxCell Cell = new DataGridViewTextBoxCell(); ?????Cell.Value = xnList2.Item(i).ChildNodes[j].InnerText; ???? ?????//添加数据到DataGridView的相应行相应列中 ?????dataGridView1.Rows[i].Cells[j] = Cell; ????} } ? 这样就可以在客户端获取你相要的数据了 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |