Binding CheckBox with Integer value in GridView:Trick


I was working on a web part basically it was an attendance web part that contains Name and Present column only and display as GridView. Name contains the full name of employee and present contains Yes/No value for that employee. I took the present column as checkbox column that displays values using checked or unchecked. Now my present data comes in integer form as 1 and 0 and checkbox takes true or false so while binding
integer value to checkbox it was throwing “Specified cast is invalid” error. After applying so many alternate and googling i couldn’t get the right way. So i developed my own way to do this…

I was binding the gridview with a data table that was querying to a custom list. Now i just add another column named as “Attendance” that contains boolean value depending upon “Present” column using expressions. So here is the code.

After getting a data table it contains two columns “Name” and “Present” with data now add a new column using code behind.

DataColumn dcAttendance = new DataColumn();
dcAttendance.DataType = System.Type.GetType(“System.Boolean”);
dcAttendance.ColumnName = “Attendance”; // New data column that will hold true and false.
dcAttendance.Expression = “Present”; // Existing data column contains values 0 and 1.
dt.Columns.Add(dcAttendance);
grdAttendance.DataSource = dt;
grdAttendance.DataBind();

Now in page inline code write:

<asp:GridView ID=”grdAttendance” runat=”server” AutoGenerateColumns=”false”>
<Columns>
<asp:BoundField DataField=”Name” HeaderText=”Name” />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID=”chkAttendance” runat=”server” Checked='<%# Bind(“Attendance”) %>’ />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Advertisements

3 thoughts on “Binding CheckBox with Integer value in GridView:Trick

  1. Hi Dhondiyal

    I have tryied to use your code in order to use an integer field in a checkboxfield of a gridview.
    In your code, what is “dt”? (dt.Columns.Add(dcAttendance);)
    (my problem is that I have an integer field (0 or 1) and just want to show a checkbox with that (I need to use integer instead of “bit” in my tables) and also my gridview needs to bind data from the sql table, so how can I bind my gridview from my sql table and also from “dt” if I try to use your solution? )
    Thanks in advance for your time and sorry my stupid question

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s