将二进制字段绑定到ASP.NET DataGrid会导致错误(Binding binary field to ASP.NET DataGrid Causes Error)

我有一个数据集,其中一个字段名为"Reviewed" 。

该数据集是人口密集的,下图显示了它的数据:

现在我试图在DataGrid中显示这个数据集:

<ASP:TemplateColumn HeaderText="Reviewed" HeaderStyle-HorizontalAlign="center" HeaderStyle-Wrap="True"> <ItemStyle Wrap="false" HorizontalAlign="center" /> <ItemTemplate> <ASP:Checkbox Checked='<%# DataBinder.Eval(Container.DataItem, "Reviewed") %>' runat="server" ID="Label22" /> </ItemTemplate> <EditItemTemplate> <Asp:Checkbox id="Textbox5" width="40" Checked='<%# DataBinder.Eval(Container.DataItem, "Reviewed") %>' runat="server" /> </EditItemTemplate> </ASP:TemplateColumn>

我收到以下错误:

异常详细信息:System.InvalidCastException:从类型'DBNull'转换为类型'Boolean'无效。

我做错了什么? 问题是DBNull来自哪里?

================================

更新:

谢谢你的好答案。 我的主要困惑点是“STUPID”XML可视化工具错误地将已审核的字段显示为已选中(如上图所示)。 我检查了数据集本身的值,并意识到所有的确都是DBNUll。

I have a dataset with one of it's fields named "Reviewed".

This dataset is popualted and below picture show it's data:

Now Im trying to show this dataset inside a DataGrid :

<ASP:TemplateColumn HeaderText="Reviewed" HeaderStyle-HorizontalAlign="center" HeaderStyle-Wrap="True"> <ItemStyle Wrap="false" HorizontalAlign="center" /> <ItemTemplate> <ASP:Checkbox Checked='<%# DataBinder.Eval(Container.DataItem, "Reviewed") %>' runat="server" ID="Label22" /> </ItemTemplate> <EditItemTemplate> <Asp:Checkbox id="Textbox5" width="40" Checked='<%# DataBinder.Eval(Container.DataItem, "Reviewed") %>' runat="server" /> </EditItemTemplate> </ASP:TemplateColumn>

I get the following Error:

Exception Details: System.InvalidCastException: Cast from type 'DBNull' to type 'Boolean' is not valid.

What I am doing wrong? Question is where DBNull comes from?

================================

Update:

Thanks for the nice answers. My main point of confusion was "STUPID" XML visualizer was wrongly showing Reviewed field as checked(as you see in the picture above). I checked the values in the dataset itself and realized all are indeed DBNUll.

最满意答案

这意味着来自数据库的一些数据为空。 您需要在分配之前检查它。您可能想要分配默认值Like。

iif((DataBinder.Eval(Container.DataItem, "Reviewed") is DbNull.Value),false, DataBinder.Eval(Container.DataItem, "Reviewed")))

您还可以创建一个检查DBNULL和null值的方法,并返回适当的值。 喜欢(它可能有语法错误,你可以纠正)

<Asp:Checkbox id="Textbox5" width="40" Checked='<%# YourMethod(Eval("Reviewed")) %>' runat="server" />

It means that some of your data coming from database is null. You need to check for that before assigning.You might want to assign a default value Like.

iif((DataBinder.Eval(Container.DataItem, "Reviewed") is DbNull.Value),false, DataBinder.Eval(Container.DataItem, "Reviewed")))

You can also create a method that checks for both DBNULL and null values and returns you the appropriate value. like (it may have syntax error that you can correct)

<Asp:Checkbox id="Textbox5" width="40" Checked='<%# YourMethod(Eval("Reviewed")) %>' runat="server" />

更多推荐