设置为单个项目集合时,Combobox Itemsource会抛出异常

时间:2015-11-03 16:26:04

标签: c# wpf xaml powershell combobox

仅使用一个条目从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

1 个答案:

答案 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中。