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

    }

}

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值