[英]C# Cannot implicitly convert type 'XXXX.Classes.Idophalen' to 'System.Collections.IEnumerable'
I making a project where I need to run an query and get that answer in a list into a Datagrid.我制作了一个项目,我需要在其中运行查询并将该答案从列表中获取到 Datagrid 中。
Here is my code: Main:这是我的代码:主要:
public UserControlDetails(string Id)
{
InitializeComponent();
var db = new Database();
var QueriAnswer = db.GetArtikel(Id);
DGVoedingswaarden.ItemsSource = QueriAnswer;
}
db.GetArtikel(Id): db.GetArtikel(Id):
public Idophalen GetArtikel(string id)
{
using (var conn = new MySqlConnection(ConnectionString))
{
conn.Open();
var query = "SELECT naam FROM tb_product WHERE Id = '" + id + "'";
var SelectArtikel = new MySqlCommand(query, conn);
var reader = SelectArtikel.ExecuteReader();
while (reader.Read())
{
var Id = reader.GetString(0);
var artikel = new Idophalen(Id);
return artikel;
}
}
return null;
}
Idophalen ( In English: GetId ) Idophalen(英文:GetId)
public class Idophalen
{
public string Id { get; set; }
public Idophalen(string Id)
{
this.Id = Id;
}
public override string ToString()
{
return string.Format("{0}", Id);
}
}
So the problem is that the code ( DGVoedingswaarden.ItemsSource = QueriAnswer;
the error: Cannot implicitly convert type 'XXXX.Classes.Idophalen' to 'System.Collections.IEnumerable'.
gives. So I don't know how to fix this or what it means. The other posts on Stackoverflow did not help me so here my case.所以问题是代码 (
DGVoedingswaarden.ItemsSource = QueriAnswer;
the error: Cannot implicitly convert type 'XXXX.Classes.Idophalen' to 'System.Collections.IEnumerable'.
给出。所以我不知道如何解决这个问题或这是什么意思 Stackoverflow 上的其他帖子对我没有帮助,所以这里是我的案例。
If you need more explanation please leave a comment如果您需要更多解释,请发表评论
Your GetArtikel
method returns a single Idophalen
.您的
GetArtikel
方法返回单个Idophalen
。 The ItemsSource
property of an ItemsControl
can only be set to an IEnumerable
such as a List<Idophalen>
. ItemsControl
的ItemsSource
属性只能设置为IEnumerable
例如List<Idophalen>
。 So you may create a list that contains only the single object returned from the database:因此,您可以创建一个仅包含从数据库返回的单个对象的列表:
DGVoedingswaarden.ItemsSource = new List<Idophalen>(1) { QueriAnswer };
The ItemsSource property accepts only an IEnumerable. ItemsSource 属性仅接受 IEnumerable。
GetArtikel()
returns an Idophalen
which is not an IEnumerable instance. GetArtikel()
返回一个Idophalen
,它不是一个 IEnumerable 实例。
you can create a list and add the result to it but it really is not a good solution.您可以创建一个列表并将结果添加到其中,但这确实不是一个好的解决方案。 you should reconsider what you are trying to do is plausible.
你应该重新考虑你试图做的事情是否合理。
anyways, this should make it work:无论如何,这应该使它起作用:
var QueriAnswer = db.GetArtikel(Id);
DGVoedingswaarden.ItemsSource = new List<Idophalen>() { QueriAnswer };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.