Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当设置为单个项集合时,Combobox Itemsource引发异常_C#_Wpf_Xaml_Powershell_Combobox - Fatal编程技术网

C# 当设置为单个项集合时,Combobox Itemsource引发异常

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

从Powershell以编程方式将
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
,那么
组合框的setter
ItemSource
就可以正常工作。该函数是在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,"")
} 

现在setter
ItemSource
接受
$rows
,但当然,空字符串将显示在
组合框中

它表示您正试图在需要ienumerable的位置设置数据行,请显示一些代码。。它需要是一个集合,即使它是一个项目,一个项目必须在集合中。