您的位置:首页 > 其它

在客户端调用WebService服务获取数据

2010-01-15 14:34 441 查看
采用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;
}
}

这样就可以在客户端获取你相要的数据了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: