TemplateColumn to display Checkbox in DataGrid

P

Paul

I am trying to display the contents of a numeric database column whose
values are restricted to 0 or 1 as a checked or unchecked checkbox in my
datagrid. I can display the database column's contents using an ordinary
bound column so I know that I am successfully retrieving the data. The
snippet from my aspx file where I try to display via a checkbox is:

<asp:BoundColumn DataField="Location" HeaderText="Location">
<HeaderStyle Width="100px"></HeaderStyle>
</asp:BoundColumn>
<asp:TemplateColumn HeaderText="Enabled">
<HeaderStyle Width="25px"></HeaderStyle>
<ItemTemplate>
<asp:CheckBox runat="server" Checked='<%#
DataBinder.Eval(Container, "DataItem.Enabled") %>'>
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>

When the page is being generated, the first row of the grid shows the proper
data in the "Location" bound column but an exception is thrown with the
message:

"Specified cast is invalid."

when the "Enabled" column in the first row is being processed. I have tried
things such as:

<asp:CheckBox runat="server" Checked='<%# ((int)DataBinder.Eval(Container,
"DataItem.Enabled"))==1 %>'>
and
<asp:CheckBox runat="server" Checked='<%# (((int)DataBinder.Eval(Container,
"DataItem.Enabled"))==1)? true : false %>'>

without any success.

Any suggestions would be appreciated.
 
S

Scott Mitchell [MVP]

I am trying to display the contents of a numeric database column whose
values are restricted to 0 or 1 as a checked or unchecked checkbox in my
datagrid. I can display the database column's contents using an ordinary
bound column so I know that I am successfully retrieving the data.

Hi Paul. One option you might want to look into is Andy Smith's free
BoundBooleanColumn control -
http://metabuilders.com/Tools/BoundBooleanColumn.aspx. Much easier than
having to muck around with TemplateColumns and databinding syntax! :)
I have tried things such as:

<asp:CheckBox runat="server" Checked='<%# ((int)DataBinder.Eval(Container,
"DataItem.Enabled"))==1 %>'>
and
<asp:CheckBox runat="server" Checked='<%# (((int)DataBinder.Eval(Container,
"DataItem.Enabled"))==1)? true : false %>'>

without any success.

Any suggestions would be appreciated.

Give the following a whirl:

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

hth

--

Scott Mitchell
(e-mail address removed)
http://www.4GuysFromRolla.com
http://www.ASPFAQs.com
http://www.ASPMessageboard.com

* When you think ASP, think 4GuysFromRolla.com!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top