仅从 odata Web Service 向 datagridview 返回一个 XML 行
本文关键字:一个 XML 返回 Web odata Service datagridview 仅从 | 更新日期: 2023-09-27 18:34:26
这是我必须从Web服务获取XMl的代码,然后我尝试将其绑定到datagridview,但我只能获得一行。
public void CreateObject()
{
const string ServerURl = "http://services.odata.org/AdventureWorksV3/AdventureWorks.svc/ProductCatalog";
HttpWebRequest request = WebRequest.Create(ServerURl) as HttpWebRequest;
request.ContentType = "application/atom+xml";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
ds.ReadXml(response.GetResponseStream());
dataGridView1.DataSource = ds.Tables[0];
}
}
private void button1_Click(object sender, EventArgs e)
{
CreateObject();
dataGridView1.DataSource = ds.Tables[0];
}
我不确定我错过了什么,它在一个wform应用程序中
这是在 Roman 的建议后更新的代码,它似乎在 ds.readxml 上抛出异常
using System;
using System.Data;
using System.Windows.Forms;
using System.Net;
namespace Odata4
{
public partial class Form1 : Form
{
public DataSet ds;
public DataTable sourcetable;
public Form1()
{
InitializeComponent();
}
public void CreateObject()
{
const string ServerURl = "http://services.odata.org/AdventureWorksV3/AdventureWorks.svc";
HttpWebRequest request = WebRequest.Create(ServerURl) as HttpWebRequest;
request.ContentType = "application/atom+xml";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
ds.ReadXml(response.GetResponseStream());
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
sourcetable.Rows.Add(dr.ItemArray);
}
}
dataGridView1.DataSource = sourcetable;
}
}
private void button1_Click(object sender, EventArgs e)
{
CreateObject();
}
}
}
由于您使用的是ds.Tables[0]
因此您只会获得DataSet
的第一个条目。尝试循环表并将结果添加到一个DataTable
,即源表。
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
sourcetable.Rows.Add(dr.ItemArray);
}
}
dataGridView1.DataSource = sourcetable;