Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Binding integer to CheckBox's Checked field

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

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>

But ASP.NET complains that

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

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"))) %>' />

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


[ANSWER] I have extended auto-generated type through partial class by adding a new property mentioned in the answer by Justin

like image 479
dance2die Avatar asked Oct 13 '09 16:10

dance2die


People also ask

How to use CheckBox in cshtml?

Checkboxes are rendered in HTML by setting the type attribute in an input element to checkbox : <input type="checkbox">

How to add CheckBox in c# MVC?

So in this article, I explain how to create a checkboxlist in MVC. Click "File" -> "New" -> "Project...". Select "ASP.Net MVC4 WebApplication", provide your Project Name, for example I used "CheckboxListDemo", then click "Ok". Now select "Internet Application", and then click "Ok".


1 Answers

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; }
}

If not, you may have success with a TypeConverter:

  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.
like image 87
Justin Grant Avatar answered Oct 09 '22 11:10

Justin Grant