ASP.NET绑定整数到CheckBox的Checked字段 [英] ASP.NET Binding integer to CheckBox's Checked field

查看:516
本文介绍了ASP.NET绑定整数到CheckBox的Checked字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以下的ListView项目模板,其中我试图将整数值绑定到CheckBox的 Checked 属性。

I have a following ListView item template, in which I am trying to bind integer value to Checked property of CheckBox.

IsUploaded 值只包含0和1 ...

IsUploaded value contains only 0 and 1...

<asp:ListView ID="trustListView" runat="server">
    <ItemTemplate>
        <asp:CheckBox ID="isUploadedCheckBox" runat="server"
            Checked='<%# Bind("IsUploaded") %>' />
    </ItemTemplate>
</asp:ListView>

但ASP.NET抱怨说

But ASP.NET complains that


异常详细信息:System.InvalidCastException:Sepcified转换无效

Exception Details: System.InvalidCastException: Sepcified cast is not valid

即使使用 DataBinder.Eval() works,

我需要一个双向绑定,因此需要使用 Bind()

Even though following code using DataBinder.Eval() works,
I need to have a 2-way binding, thus need to use Bind().

<asp:CheckBox ID="isUploadedCheckBox2" runat="server"
    Checked='<%# Convert.ToBoolean(
        DataBinder.Eval(Container.DataItem, "IsUploaded"))) %>' />

如何使用将0和1转换为布尔值Bind )

How can I convert 0's and 1's to boolean using Bind()?

[ANSWER]
通过添加 Justin的回答

推荐答案

如果您愿意改变课程在类上添加一个属性是一个布尔值

If you're willing to change the class, add a property on the class that's a boolean

public bool IsUploadedBoolean
{
   get { return IsUploaded != 0; }
   set { IsUploaded = value ? 1 : 0; }
}

如果没有,您可能会使用TypeConverter成功:

If not, you may have success with a TypeConverter:


  1. 创建自定义 TypeConverter 将处理0和1到布尔转换

  2. 坚持 TypeConverterAttribute 上的IsUploaded属性将.NET引导到您的自定义类型转换器。

  1. Create a custom TypeConverter which will handle 0 and 1 to boolean conversions
  2. Stick the TypeConverterAttribute on the IsUploaded property to direct .NET to your custom typeconverter.

这篇关于ASP.NET绑定整数到CheckBox的Checked字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆