仅使用一个条目从Powershell以编程方式将 WPF组合框的ItemSource
设置为DataRowCollection
时,我收到以下错误消息:
Ausnahme beim Festlegen von“ItemsSource”:“Der Wert “System.Data.DataRow”vom Typ“System.Data.DataRow”kann nicht in den 键入“System.Collections.IEnumerable”konvertiert werden。
大致翻译为:
设置“ItemsSource”的例外:值“System.Data.DataRow” 类型“System.Data.DataRow”无法转换为类型 “System.Collections.IEnumerable
如果我的查询导致DataRowCollection
包含两个或更多条目,那么ItemSource
的setter ComboBox
就可以正常工作了。该函数是用Powershell编写的,我已经尝试将DataRowCollection
强制转换为数组,以便为此异常做一个变通方法。
如果ItemSource
只有一个条目,我应该向DataRowCollection
制定者提供什么?
非常感谢您的帮助。
修改 以下是一些要求的代码:
$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
答案 0 :(得分:0)
我找到了一点解决方法。
现在我将单个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,"")
}
现在,设置者ItemSource
接受$rows
,但当然,空字符串将显示在ComboBox
中。