C# 当设置为单个项集合时,Combobox Itemsource引发异常
从Powershell以编程方式将C# 当设置为单个项集合时,Combobox Itemsource引发异常,c#,wpf,xaml,powershell,combobox,C#,Wpf,Xaml,Powershell,Combobox,从Powershell以编程方式将WPF组合框的ItemSource设置为DataRowCollection时,仅需一个条目,我就会收到以下错误消息: “物品来源”一词的由来是:“水资源” “System.Data.DataRow”vom Typ“System.Data.DataRow”kann nicht在den中 典型的“System.Collections.IEnumerable”konvertiert-werden 这大致可以转化为: “ItemsSource”设置异常:值“System
WPF组合框的ItemSource
设置为DataRowCollection
时,仅需一个条目,我就会收到以下错误消息:
“物品来源”一词的由来是:“水资源”
“System.Data.DataRow”vom Typ“System.Data.DataRow”kann nicht在den中
典型的“System.Collections.IEnumerable”konvertiert-werden
这大致可以转化为:
“ItemsSource”设置异常:值“System.Data.DataRow”
无法将类型为“System.Data.DataRow”的转换为类型
“System.Collections.IEnumerable
如果我的查询结果是包含两个或多个条目的DataRowCollection
,那么组合框的setterItemSource
就可以正常工作。该函数是在Powershell中编写的,我已经尝试将DataRowCollection
强制转换到数组中,以解决此异常
如果DataRowCollection
只有一个条目,那么我应该向ItemSource
设置器传递什么
非常感谢你的帮助
编辑
以下是所需的一些代码:
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | Out-Null
$connection.Close()
$rows = $dataSet.Tables[0].Rows #i am querying only one table
#$combobox is the combobox element of the wpf window
$combobox.ItemSource = $rows #If $rows has just one element, this is the point where the exception occurs
我找到了一些解决办法。
现在,我将单个DataRow
项强制转换为一个数组,并添加一个空字符串。如果不添加空字符串,则会发生相同的异常
$rows = $dataSet.Tables[0].Rows
#simple hack, to ensure this method always returns an array.
#if just one element is in Rows, wpf complains about a single datarow not being an enumerable
if($rows.Count -eq 1)
{
$rows = @($rows,"")
}
现在setterItemSource
接受$rows
,但当然,空字符串将显示在组合框中
它表示您正试图在需要ienumerable的位置设置数据行,请显示一些代码。。它需要是一个集合,即使它是一个项目,一个项目必须在集合中。