user482375
user482375

Reputation:

Having a Bit databind to a Checkbox

I have a checkbox that is databound to a field in my database and that field is a bit in the database.

This is my Checkbox:

<asp:CheckBox ID="chkDownloaded" runat="server" Checked='<%#DataBinder.Eval(Container.DataItem, "Downloaded")%>' />

When I run the code I get the following error:

Specified cast is not valid.

Any idea how to fix this?

Thanks!

Upvotes: 4

Views: 2963

Answers (5)

user1499112
user1499112

Reputation:

Option #1

Your request to Database should be like below....

Select Cast(IsNull(Downloaded, 0) as bit) as Downloaded From TableName

Option #2

In the Business Logic Layer Convert the Downloaded value to false in case of Null.

Option #3

protected void GridView_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    CheckBox c = e.Row.FindControl("chkDownloaded");
    (((YourClassName)e.Row.DataItem).YourPropertyName) == null ? false : ((YourClassName)e.Row.DataItem).YourPropertyName;
}

Upvotes: 2

Steve
Steve

Reputation: 216313

Not an ASP.NET expert, but if the column is nullable then

Checked='<%#(Eval("Downloaded") ?? 0).ToString() == "1")%>' /> 

Upvotes: -1

Juan Lopes
Juan Lopes

Reputation: 10575

Try:

<%#DataBinder.Eval(Container.DataItem, "Downloaded")!=0%>

Upvotes: 0

HatSoft
HatSoft

Reputation: 11201

you will have to convert it to boolean and bind

This way

<asp:CheckBox ID="chkDownloaded" 
runat="server" 
Checked='<%#Eval("Downloaded").ToString() == "1")%>' />

Upvotes: 1

ryudice
ryudice

Reputation: 37396

Try

DataBinder.Eval(Container.DataItem, "Downloaded") ?? false

Upvotes: 3

Related Questions