c# - Combobox Itemsource 在设置为单个项目集合时抛出异常

标签 c# wpf xaml powershell combobox

当从 Powershell 以编程方式将 WPF ComboboxItemSource 设置为 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

如果我的查询结果是一个包含两个或更多条目的 DataRowCollectionComboBox 的 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/

相关文章:

c# - 使用 NAudio 从 MP3 文件中获取音频数据

c# - 从代码中关闭 Material Design DialogHost

c# - 是否可以从列表中的项目获取索引?

c# - 从视频中提取帧的最快方法

wpf - 在 ListBoxItem.ContentTemplate 中有一个 ContentPresenter 有什么问题吗?

silverlight - 动画页边距底部 Silverlight

c# - 在 ASP.NET Web Api C# 中通过流发送和接收大文件

c# - ASP.NET MVC 会吞下提交值吗?

c# - 分类时,NEST搜索元数据丢失

c# - 列表框数据绑定(bind) NewItemPlaceholder