微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在客户端调用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;

    }

}

 

这样就可以在客户端获取你相要的数据了

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐