Задать вопрос
Shepet
@Shepet

Как исправить ошибку при выводе данных из MySQL в ListView (wpf)?

У меня возникает ошибка при попытке вывести данные из MySQL в ListView... работаю я в WPF приложении, опыта у меня маловато и самостоятельно разобраться с проблемой не получается, в силу недостаточного количества знаний и не понимания самой проблемы.

Ошибка следующая:
( System.InvalidCastException: 'Unable to cast object of type 'System.Byte[]' to type 'System.String'.' )


Детали ошибки:
( 
System.InvalidCastException
  HResult=0x80004002
  Message=Unable to cast object of type 'System.Byte[]' to type 'System.String'.
  Source=MySqlConnector
  StackTrace:
   at MySqlConnector.MySqlDataReader.GetString(Int32 ordinal)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at ShepetTTM1.Pages.FactoryPage..ctor() in C:\Users\Роман\source\repos\ShepetTTM1\ShepetTTM1\Pages\FactoryPage.xaml.cs:line 32
   at ShepetTTM1.Windows.WinMenu.BtFactory_Click(Object sender, RoutedEventArgs e) in C:\Users\Роман\source\repos\ShepetTTM1\ShepetTTM1\Windows\WinMenu.xaml.cs:line 40
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
   at System.Windows.Controls.Primitives.ButtonBase.OnClick()
   at System.Windows.Controls.Button.OnClick()
   at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
   at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
   at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
   at System.Windows.Input.InputManager.ProcessStagingArea()
   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
   at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
   at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
   at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.Run()
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run()
   at ShepetTTM1.App.Main()

 )


Вот сам код .xaml.cs :
public partial class FactoryPage : Page
    {
        public FactoryPage()
        {
            InitializeComponent();
            Lv_Fact.ItemsSource = ManiModel.init().Asus.ToList(); //выдает ошибку о типах данных   
        }
    }


Код .xaml :
<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition/>
            <RowDefinition Height="60"/>
        </Grid.RowDefinitions>

        <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" Margin="5">
            <Image Source="/Resources/lupa64.png" Margin="10,0" HorizontalAlignment="Center"/>
            <TextBox Width="900" FontSize="15"/>
            <ComboBox Margin="15,0,0,0" FontSize="20" Width="100"/>
            <ComboBox Margin="10,0" FontSize="20" Width="100"/>
        </StackPanel>

        <ListView Grid.Row="1" Name="Lv_Fact" Margin="0,10,0,50" Grid.RowSpan="2">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid Grid.Row="1" >
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="250"/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>

                        <Image Source="{Binding PictureASU, TargetNullValue={StaticResource NoPicture}}" Margin="30" VerticalAlignment="Top" />

                        <StackPanel Grid.Column="1">
                            <TextBlock FontSize="20" Margin="10">
                                <Run Text="Наименование:"/>
                                <Run Text="{Binding NameASU}"/>
                            </TextBlock>

                            <TextBlock FontSize="20" Margin="10">
                                <Run Text="Серия/Модель:"/>
                                <Run Text="{Binding SeriaModel}"/>
                            </TextBlock>

                            <TextBlock FontSize="20" Margin="10">
                                 <Run Text="Описание:"/>
                                <Run Text="{Binding DescriptionASU}"/>
                            </TextBlock>

                            <TextBlock FontSize="20" Margin="10">
                                 <Run Text="Технические характеристики:"/>
                                <Run Text="{Binding SpecificationsASU}"/>
                            </TextBlock>

                            <UniformGrid Columns="2">
                                <Button Content="Редактировать" FontSize="20" Margin="10" Background="#273849" Foreground="White"  FontFamily="Bahnschrift" Cursor="Hand"/>
                                <Button Content="Удалить" FontSize="20" Margin="10" Background="#273849" Foreground="White"  FontFamily="Bahnschrift" Cursor="Hand"/>
                            </UniformGrid>

                        </StackPanel>
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        <Button Grid.Row="2" Content="Добавить"  FontSize="20" Margin="10" Background="#273849" Foreground="White"  FontFamily="Bahnschrift" Cursor="Hand"/>
   </Grid>


Вот типы данных таблицы:
6438dc43b81a2331309355.png
  • Вопрос задан
  • 115 просмотров
Подписаться 1 Средний 2 комментария
Решения вопроса 1
idShura
@idShura
Ошибка связана с привязкой изображения в этом месте:
<Image Source="{Binding PictureASU, TargetNullValue={StaticResource NoPicture}}" Margin="30" VerticalAlignment="Top" />

Попробуй найти решение тут:
Csharp-WPF-bind-image-to-byte-array-sqlite-BLOB
How do I bind a Byte array to an Image in WPF with...
Bind Image source with image byte array
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы