如何使用listbox上的远程数据
本文关键字:数据 程数据 何使用 listbox | 更新日期: 2023-09-27 18:28:14
我正在使用web服务,所以我向应用程序添加了服务引用。我需要在listBox上显示数据。为此,我只写了以下代码,但它不起作用,我不断地收到错误。我的代码是
public Antocids()
{
InitializeComponent();
ObservableCollection<Class1> p = new ObservableCollection<Class1>();
ServiceReference3.ProductsClient client = new ServiceReference3.ProductsClient();
client.getProdDetailsCompleted += new EventHandler<ServiceReference3.getProdDetailsCompletedEventArgs>(client_getProdDetailsCompleted);
client.getProdDetailsAsync();
}
private void client_getProdDetailsCompleted(object sender, ServiceReference3.getProdDetailsCompletedEventArgs e)
{
ObservableCollection<Class1> p = e.Result; //here I'm getting the error
listBox1.DataContext=p;
}
请告诉我的确切程序
我猜您的服务引用不会返回类型为ObservableCollection<Class1>
的结果。在这种情况下,这样对待它是没有意义的。相反,当您收到结果时,您应该将元素添加到ObservableCollection中:
ObservableCollection<Class1> p = new ObservableCollection<Class1>();
public Antocids()
{
InitializeComponent();
listBox1.DataContext=p;
ServiceReference3.ProductsClient client = new ServiceReference3.ProductsClient();
client.getProdDetailsCompleted += new EventHandler<ServiceReference3.getProdDetailsCompletedEventArgs>(client_getProdDetailsCompleted);
client.getProdDetailsAsync();
}
private void client_getProdDetailsCompleted(object sender, ServiceReference3.getProdDetailsCompletedEventArgs e)
{
p.Clear(); // assuming you want to clear the data each time you get a new result
foreach(var result in e.Result)
p.Add(result) // assuming that e.Result holds an IEnumerable of Class1.
}
如果您的服务没有返回某种类型为Class1的集合,那么您将需要手动将其解析为Class1,然后将其添加到可观察的集合中。