当从 Powershell 以编程方式将 WPF Combobox 的 ItemSource
设置为 DataRowCollection
时,只有一个条目,我收到此错误消息:
Ausnahme beim Festlegen von "ItemsSource": "Der Wert "System.Data.DataRow" vom Typ "System.Data.DataRow" kann nicht in den Typ "System.Collections.IEnumerable" konvertiert werden.
大致翻译为:
Exception on setting of "ItemsSource": The value "System.Data.DataRow" of type "System.Data.DataRow" cannot be converted to type "System.Collections.IEnumerable
如果我的查询结果是一个包含两个或更多条目的 DataRowCollection
,ComboBox
的 setter ItemSource
就可以正常工作。该函数是用 Powershell 编写的,我已经尝试将 DataRowCollection
转换为数组以解决此异常。
如果 DataRowCollection
只有一个条目,我应该向 ItemSource
setter 传递什么?
非常感谢您的帮助。
编辑 这是一些要求的代码:
$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,"")
}
现在 setter ItemSource
接受 $rows
,当然,空字符串将显示在 ComboBox
中。
关于c# - Combobox Itemsource 在设置为单个项目集合时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33504196/