When setting the ItemSource
of a WPF Combobox to a DataRowCollection
programmatically from Powershell with just one entry, I'm getting this error message:
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.
which roughly translates to:
Exception on setting of "ItemsSource": The value "System.Data.DataRow" of type "System.Data.DataRow" cannot be converted to type "System.Collections.IEnumerable
If my query results in a DataRowCollection
with two or more entries, the setter ItemSource
of the ComboBox
just works fine. The function is written in Powershell and I already tried to cast the DataRowCollection
to an array to make a workaround for this exception.
What should I deliver to the ItemSource
setter, if the DataRowCollection
has just one entry?
Many thanks in advance for your help.
Edit Here is some code as requested:
$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
I found a little workaround. Now i am casting the single DataRow
item to an array and adding an empty string. Without adding an empty string, the same exception occurs.
$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,"")
}
Now the setter ItemSource
accepts the $rows
, but of course, the empty string will be shown in the ComboBox
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.