Unable to cast object of type 'System.Byte' to type 'System.String'

8.5k Views Asked by At

Queried my SQL database to fetch details into Dataset when converting the Datatable to Dataview by filtering, since being newbie to Linq, am receiving the basic conversion error.

Code:

DataView cktDv = (from clounceform in dsclounceForms.Tables["Table2"].AsEnumerable()
                                         where clounceform.Field<string>("Form_FileType_ID").Equals("5")
                                         select clounceform).CopyToDataTable().AsDataView();

Exception is

Unable to cast object of type 'System.Byte' to type 'System.String'.
System.Data.DataSetExtensions
at System.Data.DataRowExtensions.UnboxT`1.ReferenceField(Object value)
at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)
at ClounceFormsSuite.Design.CreateFormDesign.<>c.<CreateForm>b__12_0(DataRow bounceform) in myprojectfolderpath\CreateFormDesign.xaml.cs:line 115
at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
at System.Data.DataTableExtensions.LoadTableFromEnumerable[T](IEnumerable`1 source, DataTable table, Nullable`1 options, FillErrorEventHandler errorHandler)
at System.Data.DataTableExtensions.CopyToDataTable[T](IEnumerable`1 source)
at ClounceFormsSuite.Design.CreateFormDesign.CreateForm(String[] cktFileContent, String filePath, String formID) in myprojectfolderpath\CreateFormDesign.xaml.cs:line 114
at ClounceFormsSuite.Design.CreateFormDesign.UserControl_Loaded(Object sender, RoutedEventArgs e) in myprojectfolderpath\CreateFormDesign.xaml.cs:line 70

I couldnt proceed further i infact changed the casting of string to int and gives different error which is misleading me more When tried casting to int

DataView cktDataView = (from clounceform in dsclounceForms.Tables["Table2"].AsEnumerable()
                                         where clounceform.Field<int>("Form_FileType_ID") == 5
                                         select clounceform).CopyToDataTable().AsDataView();

error:

 Specified cast is not valid.
1

There are 1 best solutions below

4
Marc Gravell On BEST ANSWER

The data is a byte, not a string and not an int. Thus, you need to use Field<byte>(...):

I suspect this will work:

where clounceform.Field<byte>("Form_FileType_ID") == (byte)5